Example usage for java.util.regex Pattern MULTILINE

List of usage examples for java.util.regex Pattern MULTILINE

Introduction

In this page you can find the example usage for java.util.regex Pattern MULTILINE.

Prototype

int MULTILINE

To view the source code for java.util.regex Pattern MULTILINE.

Click Source Link

Document

Enables multiline mode.

Usage

From source file:org.mind.prebot.robot.PreBot.java

@Override
public void onMessage(String channel, String sender, String login, String hostname, String message) {
    if (!this.getIgnoredList().contains(sender)) {
        String years_str = "", months_str = "", days_str = "", hours_str = "", minutes_str = "",
                seconds_str = "";
        String[] tab = this.decryptData(message, true).trim().split(" ");
        if (tab.length > 0) {
            if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!pre") || tab[0].equalsIgnoreCase("!p"))) {
                if (tab.length > 1) {
                    String names = "";
                    for (Integer i = 1; i < tab.length; i++)
                        names += tab[i] + " ";
                    Release release = this.getMySQLManager().pre(names.trim());
                    if (release.getResults().equals(0))
                        this.sendMessage(channel,
                                this.encryptData("Nothing found for your search: " + names.trim()));
                    else {
                        if (release.getResults() > 1)
                            this.sendMessage(channel, this.encryptData(Colors.TEAL + "[ " + Colors.RED
                                    + release.getResults() + " results found! " + Colors.TEAL + "]"));
                        else
                            this.sendMessage(channel, this.encryptData(Colors.TEAL + "[ " + Colors.RED
                                    + release.getResults() + " result found! " + Colors.TEAL + "]"));
                        Integer years = release.getDiffDate() / 31536000;
                        Integer yearsMod = release.getDiffDate() % 31536000;
                        if (years == 1)
                            years_str = years + " year ";
                        else if (years > 1)
                            years_str = years + " years ";
                        Integer months = yearsMod / 2592000;
                        Integer monthsMod = yearsMod % 2592000;
                        if (months == 1)
                            months_str = months + " month ";
                        else if (months > 1)
                            months_str = months + " months ";
                        Integer days = monthsMod / 86400;
                        Integer daysMod = monthsMod % 86400;
                        if (days == 1)
                            days_str = days + " day ";
                        else if (days > 1)
                            days_str = days + " days ";
                        Integer hours = daysMod / 3600;
                        Integer hoursMod = daysMod % 3600;
                        if (hours == 1)
                            hours_str = hours + " hour ";
                        else if (hours > 1)
                            hours_str = hours + " hours ";
                        Integer minutes = hoursMod / 60;
                        if (minutes == 1)
                            minutes_str = minutes + " minute ";
                        else if (minutes > 1)
                            minutes_str = minutes + " minutes ";
                        Integer seconds = hoursMod % 60;
                        if (seconds == 1)
                            seconds_str = seconds + " second ";
                        else
                            seconds_str = seconds + " seconds ";
                        if (release.getChecked().equals("1") || release.getNuked().equals("0"))
                            this.sendMessage(channel,
                                    this.encryptData(Colors.TEAL + "[" + Colors.YELLOW + " PRED " + Colors.TEAL
                                            + "][ " + Utils.getCategoryCode(release.getCategory())
                                            + release.getCategory() + Colors.TEAL + " ][ " + Colors.LIGHT_GRAY
                                            + release.getName() + Colors.TEAL + " ][ " + Colors.LIGHT_GRAY
                                            + years_str + months_str + days_str + hours_str + minutes_str
                                            + seconds_str + "ago (" + release.getDate() + ") " + Colors.TEAL
                                            + "][ " + Colors.OLIVE + release.getSize() + Colors.TEAL + " ]"
                                            + (release.getChecked().equals("1") ? ""
                                                    : "[ " + Colors.RED + "UNCHECKED" + Colors.TEAL + " ]")));
                        else
                            this.sendMessage(channel,
                                    this.encryptData(Colors.TEAL + "[" + Colors.RED + " NUKED " + Colors.TEAL
                                            + "][ " + Utils.getCategoryCode(release.getCategory())
                                            + release.getCategory() + Colors.TEAL + " ][ " + Colors.LIGHT_GRAY
                                            + release.getName() + Colors.TEAL + " ][ " + Colors.LIGHT_GRAY
                                            + years_str + months_str + days_str + hours_str + minutes_str
                                            + seconds_str + "ago (" + release.getDate() + ") " + Colors.TEAL
                                            + "][ " + Colors.RED + release.getReason() + Colors.TEAL + " ][ "
                                            + Colors.OLIVE + release.getSize() + Colors.TEAL + " ]"));
                    }/*from  www.j a  va 2  s  .co m*/
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!dupenuke") || tab[0].equalsIgnoreCase("!dnu"))) {
                String names = "";
                String limit = "10";
                for (Integer i = 1; i < tab.length; i++) {
                    if (tab[i].contains("limit"))
                        limit = tab[i].substring(tab[i].indexOf("limit:") + 6, tab[i].length());
                    else
                        names += tab[i] + " ";
                }
                LinkedList<Release> releases = null;
                if (tab.length > 1)
                    releases = this.getMySQLManager().dupenuke(names.trim(), limit);
                else
                    releases = this.getMySQLManager().dupenuke("", limit);
                if (releases.isEmpty())
                    this.sendMessage(channel, this.encryptData(
                            "Nothing found for your search: " + (tab.length > 1 ? names.trim() : "")));
                else {
                    if (releases.get(0).getResults() > 1)
                        this.sendMessage(channel,
                                this.encryptData("Sending " + Colors.OLIVE + sender + Colors.LIGHT_GRAY
                                        + " last " + Colors.OLIVE + releases.get(0).getResults() + Colors.RED
                                        + " nuked " + Colors.LIGHT_GRAY + "results."));
                    else
                        this.sendMessage(channel,
                                this.encryptData("Sending " + Colors.OLIVE + sender + Colors.LIGHT_GRAY
                                        + " last " + Colors.OLIVE + releases.get(0).getResults() + Colors.RED
                                        + " nuked " + Colors.LIGHT_GRAY + "results"));
                    for (Release release : releases) {
                        Integer years = release.getDiffDate() / 31536000;
                        Integer yearsMod = release.getDiffDate() % 31536000;
                        if (years == 1)
                            years_str = years + " year ";
                        else if (years > 1)
                            years_str = years + " years ";
                        Integer months = yearsMod / 2592000;
                        Integer monthsMod = yearsMod % 2592000;
                        if (months == 1)
                            months_str = months + " month ";
                        else if (months > 1)
                            months_str = months + " months ";
                        Integer days = monthsMod / 86400;
                        Integer daysMod = monthsMod % 86400;
                        if (days == 1)
                            days_str = days + " day ";
                        else if (days > 1)
                            days_str = days + " days ";
                        Integer hours = daysMod / 3600;
                        Integer hoursMod = daysMod % 3600;
                        if (hours == 1)
                            hours_str = hours + " hour ";
                        else if (hours > 1)
                            hours_str = hours + " hours ";
                        Integer minutes = hoursMod / 60;
                        if (minutes == 1)
                            minutes_str = minutes + " minute ";
                        else if (minutes > 1)
                            minutes_str = minutes + " minutes ";
                        Integer seconds = hoursMod % 60;
                        if (seconds == 1)
                            seconds_str = seconds + " second ";
                        else
                            seconds_str = seconds + " seconds ";
                        this.sendMessage(sender,
                                this.encryptData(Colors.TEAL + "[" + Colors.RED + " NUKED " + Colors.TEAL
                                        + "][ " + Utils.getCategoryCode(release.getCategory())
                                        + release.getCategory() + Colors.TEAL + " ][ " + Colors.LIGHT_GRAY
                                        + release.getName() + Colors.TEAL + " ][ " + Colors.LIGHT_GRAY
                                        + years_str + months_str + days_str + hours_str + minutes_str
                                        + seconds_str + "ago (" + release.getDate() + ") " + Colors.TEAL + "][ "
                                        + Colors.RED + release.getReason() + Colors.TEAL + " ][ " + Colors.OLIVE
                                        + release.getSize() + Colors.TEAL + " ]"));
                    }
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!dupe") || tab[0].equalsIgnoreCase("!d"))) {
                String names = "";
                String limit = "10";
                for (Integer i = 1; i < tab.length; i++) {
                    if (tab[i].contains("limit"))
                        limit = tab[i].substring(tab[i].indexOf("limit:") + 6, tab[i].length());
                    else
                        names += tab[i] + " ";
                }
                LinkedList<Release> releases = null;
                if (tab.length > 1)
                    releases = this.getMySQLManager().dupe(names.trim(), limit);
                else
                    releases = this.getMySQLManager().dupe("", limit);
                if (releases.isEmpty())
                    this.sendMessage(channel, this.encryptData(
                            "Nothing found for your search: " + (tab.length > 1 ? names.trim() : "")));
                else {
                    if (releases.get(0).getResults() > 1)
                        this.sendMessage(channel,
                                this.encryptData("Sending " + Colors.OLIVE + sender + Colors.LIGHT_GRAY
                                        + " last " + Colors.OLIVE + releases.get(0).getResults()
                                        + Colors.LIGHT_GRAY + " results."));
                    else
                        this.sendMessage(channel,
                                this.encryptData("Sending " + Colors.OLIVE + sender + Colors.LIGHT_GRAY
                                        + " last " + Colors.OLIVE + releases.get(0).getResults()
                                        + Colors.LIGHT_GRAY + " result."));
                    for (Release release : releases) {
                        Integer years = release.getDiffDate() / 31536000;
                        Integer yearsMod = release.getDiffDate() % 31536000;
                        if (years == 1)
                            years_str = years + " year ";
                        else if (years > 1)
                            years_str = years + " years ";
                        Integer months = yearsMod / 2592000;
                        Integer monthsMod = yearsMod % 2592000;
                        if (months == 1)
                            months_str = months + " month ";
                        else if (months > 1)
                            months_str = months + " months ";
                        Integer days = monthsMod / 86400;
                        Integer daysMod = monthsMod % 86400;
                        if (days == 1)
                            days_str = days + " day ";
                        else if (days > 1)
                            days_str = days + " days ";
                        Integer hours = daysMod / 3600;
                        Integer hoursMod = daysMod % 3600;
                        if (hours == 1)
                            hours_str = hours + " hour ";
                        else if (hours > 1)
                            hours_str = hours + " hours ";
                        Integer minutes = hoursMod / 60;
                        if (minutes == 1)
                            minutes_str = minutes + " minute ";
                        else if (minutes > 1)
                            minutes_str = minutes + " minutes ";
                        Integer seconds = hoursMod % 60;
                        if (seconds == 1)
                            seconds_str = seconds + " second ";
                        else
                            seconds_str = seconds + " seconds ";
                        if (release.getChecked().equals("1") || release.getNuked().equals("0"))
                            this.sendMessage(sender,
                                    this.encryptData(Colors.TEAL + "[" + Colors.YELLOW + " PRED " + Colors.TEAL
                                            + "][ " + Utils.getCategoryCode(release.getCategory())
                                            + release.getCategory() + Colors.TEAL + "][ " + Colors.LIGHT_GRAY
                                            + release.getName() + Colors.TEAL + "][ " + Colors.LIGHT_GRAY
                                            + years_str + months_str + days_str + hours_str + minutes_str
                                            + seconds_str + "ago (" + release.getDate() + ") " + Colors.TEAL
                                            + "][ " + Colors.OLIVE + release.getSize() + Colors.TEAL + " ]"
                                            + (release.getChecked().equals("1") ? ""
                                                    : "[ " + Colors.RED + "UNCHECKED" + Colors.TEAL + " ]")));
                        else
                            this.sendMessage(sender,
                                    this.encryptData(Colors.TEAL + "[" + Colors.RED + " NUKED " + Colors.TEAL
                                            + "][ " + Utils.getCategoryCode(release.getCategory())
                                            + release.getCategory() + Colors.TEAL + " ][ " + Colors.LIGHT_GRAY
                                            + release.getName() + Colors.TEAL + " ][ " + Colors.LIGHT_GRAY
                                            + years_str + months_str + days_str + hours_str + minutes_str
                                            + seconds_str + "ago (" + release.getDate() + ") " + Colors.TEAL
                                            + "][ " + Colors.RED + release.getReason() + Colors.TEAL + " ][ "
                                            + Colors.OLIVE + release.getSize() + Colors.TEAL + " ]"));
                    }
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!nuke") || tab[0].equalsIgnoreCase("!nk"))) {
                if (this.getNukerList().contains(sender)) {
                    String names = "";
                    for (Integer i = 2; i < tab.length; i++)
                        names += tab[i] + " ";
                    if (tab.length > 2) {
                        Integer ret = this.getMySQLManager().nuke(tab[1], names.trim());
                        if (ret > 0)
                            this.sendMessage(channel,
                                    this.encryptData(Colors.OLIVE + tab[1] + Colors.LIGHT_GRAY
                                            + " has been successfully " + Colors.RED + "nuked"
                                            + Colors.LIGHT_GRAY + "!"));
                        else
                            this.sendMessage(channel,
                                    this.encryptData(Colors.OLIVE + tab[1] + Colors.LIGHT_GRAY
                                            + " has not been successfully " + Colors.RED + "nuked"
                                            + Colors.LIGHT_GRAY + "!"));
                    }
                } else
                    this.sendMessage(channel, this.encryptData(sender + ": You've to be a nuker to do this."));
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!unnuke") || tab[0].equalsIgnoreCase("!un"))) {
                if (this.getNukerList().contains(sender)) {
                    String names = "";
                    for (Integer i = 2; i < tab.length; i++)
                        names += tab[i] + " ";
                    if (tab.length > 2) {
                        Integer ret = this.getMySQLManager().unnuke(tab[1], names.trim());
                        if (ret > 0)
                            this.sendMessage(channel,
                                    this.encryptData(Colors.OLIVE + tab[1] + Colors.LIGHT_GRAY
                                            + " has been successfully " + Colors.DARK_GREEN + "unnuked"
                                            + Colors.LIGHT_GRAY + "!"));
                        else
                            this.sendMessage(channel,
                                    this.encryptData(Colors.OLIVE + tab[1] + Colors.LIGHT_GRAY
                                            + " has not been successfully " + Colors.DARK_GREEN + "unnuked"
                                            + Colors.LIGHT_GRAY + "!"));
                    }
                } else
                    this.sendMessage(channel, this.encryptData(sender + ": You've to be a nuker to do this."));
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!addpre") || tab[0].equalsIgnoreCase("!ap"))) {
                if (this.getNukerList().contains(sender)) {
                    String names = "";
                    for (Integer i = 3; i < tab.length; i++)
                        names += tab[i] + " ";
                    if (tab.length > 3) {
                        Integer ret = this.getMySQLManager().addpre(tab[1], tab[2], names.trim());
                        if (ret > 0)
                            this.sendMessage(channel,
                                    this.encryptData(Colors.OLIVE + tab[1] + Colors.LIGHT_GRAY
                                            + " has been successfully " + Colors.DARK_GREEN + "addpred"
                                            + Colors.LIGHT_GRAY + "!"));
                        else
                            this.sendMessage(channel,
                                    this.encryptData(Colors.OLIVE + tab[1] + Colors.LIGHT_GRAY
                                            + " has not been successfully " + Colors.DARK_GREEN + "addpred"
                                            + Colors.LIGHT_GRAY + "!"));
                    }
                } else
                    this.sendMessage(channel, this.encryptData(sender + ": You've to be a nuker to do this."));
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!delpre") || tab[0].equalsIgnoreCase("!dp"))) {
                if (this.getNukerList().contains(sender)) {
                    if (tab.length > 1) {
                        Integer ret = this.getMySQLManager().delpre(tab[1]);
                        if (ret > 0)
                            this.sendMessage(channel,
                                    this.encryptData(Colors.OLIVE + tab[1] + Colors.LIGHT_GRAY
                                            + " has been successfully " + Colors.DARK_GREEN + "delpred"
                                            + Colors.LIGHT_GRAY + "!"));
                        else
                            this.sendMessage(channel,
                                    this.encryptData(Colors.OLIVE + tab[1] + Colors.LIGHT_GRAY
                                            + " has not been successfully " + Colors.DARK_GREEN + "delpred"
                                            + Colors.LIGHT_GRAY + "!"));
                    }
                } else
                    this.sendMessage(channel, this.encryptData(sender + ": You've to be a nuker to do this."));
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindChannel())
                    && tab[0].equalsIgnoreCase("!vdm")) {
                List<String> vdms = Utils.getMatcher(Utils.VDMRegex, Utils.getCode(Utils.VDMFeed),
                        Pattern.MULTILINE);
                if (!vdms.isEmpty()) {
                    String vdm = vdms.get(new Random().nextInt(vdms.size()));
                    vdm = StringEscapeUtils.unescapeHtml4(vdm);
                    vdm = vdm.substring(30).replaceAll("[\r\n]+", "").replaceAll(" {2,}", " ").trim();
                    this.sendMessage(channel, this.encryptData(Colors.TEAL + "[" + Colors.BROWN + " VDM "
                            + Colors.TEAL + "] :: [ " + Colors.DARK_GREEN + vdm + Colors.TEAL + " ]"));
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindChannel())
                    && tab[0].equalsIgnoreCase("!cnf")) {
                List<String> cnfs = Utils.getMatcher(Utils.CNFRegex, Utils.getCode(Utils.CNFPage),
                        Pattern.MULTILINE);
                if (!cnfs.isEmpty()) {
                    String cnf = cnfs.get(new Random().nextInt(cnfs.size()));
                    cnf = StringEscapeUtils.unescapeHtml4(cnf);
                    cnf = cnf.substring(cnf.indexOf(">") + 1, cnf.indexOf("</div>")).replaceAll("[\r\n]+", "")
                            .replaceAll(" {2,}", " ").trim();
                    this.sendMessage(channel, this.encryptData(Colors.TEAL + "[" + Colors.RED + " CNF "
                            + Colors.TEAL + "] :: [ " + Colors.DARK_GREEN + cnf + Colors.TEAL + " ]"));
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindChannel())
                    && (tab[0].equalsIgnoreCase("!slap") || tab[0].equalsIgnoreCase("!s"))) {
                if (this.getSlaps() < this.getSlapsRandom())
                    this.setSlaps(this.getSlaps() + 1);
                else {
                    this.kick(channel, sender, this.encryptData("Sorry, you loose this time ^^"));
                    this.setSlaps(0);
                    this.setSlapsRandom(new Random().nextInt(26));
                }
            } else if (tab[0].equalsIgnoreCase("!kick") || tab[0].equalsIgnoreCase("!k")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 2) {
                        String names = "";
                        for (Integer i = 2; i < tab.length; i++)
                            names += tab[i] + " ";
                        this.kick(channel, tab[1], this.encryptData(names.trim()));
                    } else
                        this.kick(channel, tab[1]);
                }
            } else if (tab[0].equalsIgnoreCase("!ban") || tab[0].equalsIgnoreCase("!b")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 1)
                        this.ban(channel, tab[1]);
                }
            } else if (tab[0].equalsIgnoreCase("!mode") || tab[0].equalsIgnoreCase("!m")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 2)
                        this.setMode(channel, tab[1] + " " + tab[2]);
                }
            } else if (tab[0].equalsIgnoreCase("!message") || tab[0].equalsIgnoreCase("!msg")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 2) {
                        String names = "";
                        for (Integer i = 2; i < tab.length; i++)
                            names += tab[i] + " ";
                        this.sendMessage(tab[1], this.encryptData(names.trim()));
                    }
                }
            } else if (tab[0].equalsIgnoreCase("!action") || tab[0].equalsIgnoreCase("!a")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 2) {
                        String names = "";
                        for (Integer i = 2; i < tab.length; i++)
                            names += tab[i] + " ";
                        this.sendAction(tab[1], this.encryptData(names.trim()));
                    }
                }
            } else if (tab[0].equalsIgnoreCase("!notice") || tab[0].equalsIgnoreCase("!n")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 2) {
                        String names = "";
                        for (Integer i = 2; i < tab.length; i++)
                            names += tab[i] + " ";
                        this.sendNotice(tab[1], this.encryptData(names.trim()));
                    }
                }
            } else if (tab[0].equalsIgnoreCase("!ignore") || tab[0].equalsIgnoreCase("!i")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 1) {
                        if (!this.getIgnoredList().contains(tab[1]))
                            this.getIgnoredList().add(tab[1]);
                    }
                }
            } else if (tab[0].equalsIgnoreCase("!unignore") || tab[0].equalsIgnoreCase("!ui")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 1) {
                        if (this.getIgnoredList().contains(tab[1]))
                            this.getIgnoredList().remove(tab[1]);
                    }
                }
            } else if (tab[0].equalsIgnoreCase("!addnuker") || tab[0].equalsIgnoreCase("!an")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 1) {
                        if (!this.getNukerList().contains(tab[1]))
                            this.getNukerList().add(tab[1]);
                    }
                }
            } else if (tab[0].equalsIgnoreCase("!delnuker") || tab[0].equalsIgnoreCase("!dn")) {
                if (sender.equals("BaYbEE")) {
                    if (tab.length > 1) {
                        if (this.getNukerList().contains(tab[1]))
                            this.getNukerList().remove(tab[1]);
                    }
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!showrequest") || tab[0].equalsIgnoreCase("!sr"))) {
                if (tab.length > 1) {
                    String names = "";
                    for (Integer i = 1; i < tab.length; i++)
                        names += tab[i] + " ";
                    Request request = this.getMySQLManager().showrequest(names.trim());
                    if (request.getResults().equals(0))
                        this.sendMessage(channel,
                                this.encryptData("Nothing found for your search: " + names.trim()));
                    else {
                        if (request.getResults() > 1)
                            this.sendMessage(channel, this.encryptData(
                                    "\00310[\00304 " + request.getResults() + " results found! \00310]"));
                        else
                            this.sendMessage(channel, this.encryptData(
                                    "\00310[\00304 " + request.getResults() + " result found! \00310]"));
                        Integer years = request.getDiffDate() / 31536000;
                        Integer yearsMod = request.getDiffDate() % 31536000;
                        if (years == 1)
                            years_str = years + " year ";
                        else if (years > 1)
                            years_str = years + " years ";
                        Integer months = yearsMod / 2592000;
                        Integer monthsMod = yearsMod % 2592000;
                        if (months == 1)
                            months_str = months + " month ";
                        else if (months > 1)
                            months_str = months + " months ";
                        Integer days = monthsMod / 86400;
                        Integer daysMod = monthsMod % 86400;
                        if (days == 1)
                            days_str = days + " day ";
                        else if (days > 1)
                            days_str = days + " days ";
                        Integer hours = daysMod / 3600;
                        Integer hoursMod = daysMod % 3600;
                        if (hours == 1)
                            hours_str = hours + " hour ";
                        else if (hours > 1)
                            hours_str = hours + " hours ";
                        Integer minutes = hoursMod / 60;
                        if (minutes == 1)
                            minutes_str = minutes + " minute ";
                        else if (minutes > 1)
                            minutes_str = minutes + " minutes ";
                        Integer seconds = hoursMod % 60;
                        if (seconds == 1)
                            seconds_str = seconds + " second ";
                        else
                            seconds_str = seconds + " seconds ";
                        if (request.getFilled())
                            this.sendMessage(channel, this.encryptData("\00310[\00308 REQ \00310] [\00315 "
                                    + request.getRequest() + " \00310] [\00315 " + years_str + months_str
                                    + days_str + hours_str + minutes_str + seconds_str + "ago ("
                                    + (request.getRequestDate()) + ") \00310] [ \00307Requested by: \00315"
                                    + request.getRequestBy() + " \00310] [ \00307Filled by: \00315"
                                    + request.getFilledBy() + " \00310]"));
                        else
                            this.sendMessage(channel, this.encryptData("\00310[\00308 REQ \00310] [\00315 "
                                    + request.getRequest() + " \00310] [\00315 " + years_str + months_str
                                    + days_str + hours_str + minutes_str + seconds_str + "ago ("
                                    + request.getRequestDate() + ") \00310] [ \00307Requested by: \00315"
                                    + request.getRequestBy() + " \00310]"));
                    }
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!addrequest") || tab[0].equalsIgnoreCase("!ar"))) {
                String names = "";
                for (Integer i = 1; i < tab.length; i++)
                    names += tab[i] + " ";
                if (tab.length > 1) {
                    Request request = new Request();
                    request.setRequest(names.trim());
                    request.setRequestBy(sender);
                    request.setRequestDate(null);
                    request.setFilled(false);
                    request.setFilledBy("");
                    Integer ret = this.getMySQLManager().addrequest(request);
                    if (ret > 0)
                        this.sendMessage(channel, this.encryptData("\00307" + names.trim()
                                + "\00315 has been successfully \00304requested\00315!"));
                    else
                        this.sendMessage(channel, this.encryptData("\00307" + names.trim()
                                + "\00315 has not been successfully \00304requested\00315!"));
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!fillrequest") || tab[0].equalsIgnoreCase("!fr"))) {
                String names = "";
                for (Integer i = 1; i < tab.length; i++)
                    names += tab[i] + " ";
                if (tab.length > 1) {
                    Integer ret = this.getMySQLManager().fillrequest(names.trim(), sender);
                    if (ret > 0)
                        this.sendMessage(channel, this.encryptData(
                                "\00307" + names.trim() + "\00315 has been successfully \00304filled\00315!"));
                    else
                        this.sendMessage(channel, this.encryptData("\00307" + names.trim()
                                + "\00315 has not been successfully \0030filled\00315!"));
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!duperequest") || tab[0].equalsIgnoreCase("!dr"))) {
                String names = "";
                String limit = "10";
                for (Integer i = 1; i < tab.length; i++) {
                    if (tab[i].contains("limit"))
                        limit = tab[i].substring(tab[i].indexOf("limit:") + 6, tab[i].length());
                    else
                        names += tab[i] + " ";
                }
                LinkedList<Request> requests = null;
                if (tab.length > 1)
                    requests = this.getMySQLManager().duperequest(names.trim(), limit);
                else
                    requests = this.getMySQLManager().duperequest("", limit);
                if (requests.isEmpty())
                    this.sendMessage(channel, this.encryptData(
                            "Nothing found for your search: " + (tab.length > 1 ? names.trim() : "")));
                else {
                    if (requests.get(0).getResults() > 1)
                        this.sendMessage(channel, this.encryptData("Sending \00307" + sender
                                + "\00315 last \00307" + requests.get(0).getResults() + "\00315 results."));
                    else
                        this.sendMessage(channel, this.encryptData("Sending \00307" + sender
                                + "\00315 last \00307" + requests.get(0).getResults() + "\00315 result."));
                    for (Request request : requests) {
                        Integer years = request.getDiffDate() / 31536000;
                        Integer yearsMod = request.getDiffDate() % 31536000;
                        if (years == 1)
                            years_str = years + " year ";
                        else if (years > 1)
                            years_str = years + " years ";
                        Integer months = yearsMod / 2592000;
                        Integer monthsMod = yearsMod % 2592000;
                        if (months == 1)
                            months_str = months + " month ";
                        else if (months > 1)
                            months_str = months + " months ";
                        Integer days = monthsMod / 86400;
                        Integer daysMod = monthsMod % 86400;
                        if (days == 1)
                            days_str = days + " day ";
                        else if (days > 1)
                            days_str = days + " days ";
                        Integer hours = daysMod / 3600;
                        Integer hoursMod = daysMod % 3600;
                        if (hours == 1)
                            hours_str = hours + " hour ";
                        else if (hours > 1)
                            hours_str = hours + " hours ";
                        Integer minutes = hoursMod / 60;
                        if (minutes == 1)
                            minutes_str = minutes + " minute ";
                        else if (minutes > 1)
                            minutes_str = minutes + " minutes ";
                        Integer seconds = hoursMod % 60;
                        if (seconds == 1)
                            seconds_str = seconds + " second ";
                        else
                            seconds_str = seconds + " seconds ";
                        if (request.getFilled())
                            this.sendMessage(sender, this.encryptData("\00310[\00308 REQ \00310] [\00315 "
                                    + request.getRequest() + " \00310] [\00315 " + years_str + months_str
                                    + days_str + hours_str + minutes_str + seconds_str + "ago ("
                                    + request.getRequestDate() + ") \00310] [ \00307Requested by: \00315"
                                    + request.getRequestBy() + " \00310] [ \00307Filled by: \00315"
                                    + request.getFilledBy() + " \00310]"));
                        else
                            this.sendMessage(sender, this.encryptData("\00310[\00308 REQ \00310] [\00315 "
                                    + request.getRequest() + " \00310] [\00315 " + years_str + months_str
                                    + days_str + hours_str + minutes_str + seconds_str + "ago ("
                                    + request.getRequestDate() + ") \00310] [ \00307Requested by: \00315"
                                    + request.getRequestBy() + " \00310]"));
                    }
                }
            } else if (channel.equalsIgnoreCase(this.getParent().getIRCMindPreSearchChannel())
                    && (tab[0].equalsIgnoreCase("!group") || tab[0].equalsIgnoreCase("!g"))) {
                Group group = this.getMySQLManager().group();
                this.sendMessage(channel,
                        this.encryptData(Colors.DARK_GRAY + "Total Releases: " + Colors.GREEN
                                + group.getTotalReleases() + Colors.DARK_GRAY + " Total Nuked: " + Colors.RED
                                + group.getTotalNukes() + Colors.DARK_GRAY + " Total Unuked: " + Colors.OLIVE
                                + group.getTotalUnnukes()));
                this.sendMessage(channel,
                        this.encryptData(Colors.DARK_GRAY + "First Pre: " + Colors.LIGHT_GRAY + "["
                                + Utils.getCategoryCode(group.getCategoryFirstPre())
                                + group.getCategoryFirstPre() + Colors.LIGHT_GRAY + "] " + group.getFirstPre()
                                + " [" + group.getDateFirstPre() + "]"));
                this.sendMessage(channel, this.encryptData(Colors.DARK_GRAY + "Last Pre: " + Colors.LIGHT_GRAY
                        + "[" + Utils.getCategoryCode(group.getCategoryLastPre()) + group.getCategoryLastPre()
                        + Colors.LIGHT_GRAY + "] " + group.getLastPre() + " [" + group.getDateLastPre() + "]"));
            } else {
                for (String t : tab) {
                    if (!Utils.getMatcher(Utils.URLRegex, t, Pattern.DOTALL).isEmpty()) {
                        String title = Utils.getTitleMatcher(Utils.getCode(t));
                        if (title != null) {
                            title = StringEscapeUtils.unescapeHtml4(title);
                            title = title.substring(7, title.length() - 8).replaceAll("[\r\n]+", "")
                                    .replaceAll(" {2,}", " ").trim();
                            this.sendMessage(channel,
                                    this.encryptData("\00310[\00303 Title:\00307 " + title + " \00310]"));
                        }
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.birt.report.engine.emitter.docx.writer.BasicComponent.java

private void writeHtmlText(IForeignContent foreignContent)
        throws EncoderException, UnsupportedEncodingException {
    mhtPartWriter.println();/*from   w  w w  .  jav a2 s .  c om*/
    mhtPartWriter.println("--" + BOUNDARY);
    mhtPartWriter.println("Content-Type: text/html; charset=\"gb2312\"");
    mhtPartWriter.println("Content-Transfer-Encoding: quoted-printable");
    mhtPartWriter.println();

    StringBuffer htmlBuffer = new StringBuffer();
    String foreignText = foreignContent.getRawValue().toString();
    String headInformation = null;
    String htmlAttribute = null;
    Pattern pattern = Pattern.compile(validHtml, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    Matcher matcher = pattern.matcher(foreignText);
    if (matcher.find() && matcher.group(0).length() == foreignText.length()) {
        headInformation = matcher.group(1);
        htmlAttribute = matcher.group(2);
        foreignText = matcher.group(3);
    }
    mhtPartWriter.print("=EF=BB=BF");
    if (headInformation != null) {
        htmlBuffer.append(headInformation + " ");
    }
    htmlBuffer.append("<html");
    if (htmlAttribute != null) {
        htmlBuffer.append(" " + htmlAttribute);
    }
    htmlBuffer.append(">");
    IStyle style = foreignContent.getComputedStyle();
    buildStyleClass(style, htmlBuffer);
    buildHtmlBody(foreignContent, foreignText, style, htmlBuffer);
    mhtPartWriter.print("</html>");
}

From source file:org.oscarehr.casemgmt.service.CaseManagementManager.java

/**
 * substitute function for updateCurrentIssueToCPP We don't want to clobber existing text in ongoing concerns all we want to do is remove the issue description
 **///w w w . j a va2 s  .c  o m
public void removeIssueFromCPP(String demoNo, CaseManagementIssue issue) {
    CaseManagementCPP cpp = caseManagementCPPDAO.getCPP(demoNo);
    if (cpp == null) {
        logger.error("Cannot remove issue: No CPP found for demographic: " + demoNo);
        return;
    }

    String ongoing = cpp.getOngoingConcerns();
    String newOngoing;
    String description;

    description = issue.getIssue().getDescription();
    Pattern pattern = Pattern.compile("^" + description + "$", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(ongoing);

    if (matcher.find()) {
        newOngoing = matcher.replaceFirst("");

        cpp.setOngoingConcerns(newOngoing);
        caseManagementCPPDAO.saveCPP(cpp);

        OscarProperties properties = OscarProperties.getInstance();
        if (!Boolean.parseBoolean(properties.getProperty("AbandonOldChart", "false"))) {
            echartDAO.updateEchartOngoing(cpp);
        }
    }
}

From source file:ru.histone.v2.evaluator.Evaluator.java

private CompletableFuture<EvalNode> processRegExp(ExpAstNode node) {
    return CompletableFuture.supplyAsync(() -> {
        final LongAstNode flagsNumNode = node.getNode(1);
        final long flagsNum = flagsNumNode.getValue();

        int flags = 0;
        if ((flagsNum & AstRegexType.RE_IGNORECASE.getId()) != 0) {
            flags |= Pattern.CASE_INSENSITIVE;
        }/*from   w w  w.j ava  2  s . c  o m*/
        if ((flagsNum & AstRegexType.RE_MULTILINE.getId()) != 0) {
            flags |= Pattern.MULTILINE;
        }

        final boolean isGlobal = (flagsNum & AstRegexType.RE_GLOBAL.getId()) != 0;
        final StringAstNode expNode = node.getNode(0);
        final String exp = expNode.getValue();
        final Pattern pattern = Pattern.compile(exp, flags);
        return new RegexEvalNode(new HistoneRegex(isGlobal, pattern));
    });
}

From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * Detect HTML in the first KB to prevent against potential security issue with IE/Safari/Opera file type auto detection bug. Returns
 * true if file contain insecure HTML code at the beginning.
 *
 * @param item file upload item/*w  w  w  .  jav  a2s . c  o m*/
 * @return true if detected.
 * @throws IOException when io error occurs.
 */
public static boolean detectHtml(final FileItem item) throws IOException {
    byte[] buff = new byte[MAX_BUFFER_SIZE];
    InputStream is = null;
    try {
        is = item.getInputStream();
        is.read(buff, 0, MAX_BUFFER_SIZE);
        String content = new String(buff);
        content = content.toLowerCase().trim();

        if (Pattern
                .compile("<!DOCTYPE\\W+X?HTML.+", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(content).matches()) {
            return true;
        }

        String[] tags = { "<body", "<head", "<html", "<img", "<pre", "<script", "<table", "<title" };

        for (String tag : tags) {
            if (content.indexOf(tag) != -1) {
                return true;
            }
        }

        if (Pattern
                .compile("type\\s*=\\s*[\'\"]?\\s*(?:\\w*/)?(?:ecma|java)",
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(content).find()) {
            return true;
        }

        if (Pattern
                .compile("(?:href|src|data)\\s*=\\s*[\'\"]?\\s*(?:ecma|java)script:",
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(content).find()) {
            return true;
        }

        if (Pattern
                .compile("url\\s*\\(\\s*[\'\"]?\\s*(?:ecma|java)script:",
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(content).find()) {
            return true;
        }
    } catch (IOException e) {
        throw e;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return false;
}

From source file:org.oscarehr.casemgmt.service.CaseManagementManager.java

/**
 * Substitute for updateCurrentIssueToCPP we replace old issue with new without clobbering existing text
 **///  ww  w . ja va2 s .  co m
public void changeIssueInCPP(String demoNo, String origIssueDesc, String newIssueDesc) {
    CaseManagementCPP cpp = caseManagementCPPDAO.getCPP(demoNo);
    if (cpp == null) {
        logger.error("Cannot change issue: No CPP found for demographic: " + demoNo);
        return;
    }
    String ongoing = cpp.getOngoingConcerns();
    String newOngoing;

    Pattern pattern = Pattern.compile("^" + origIssueDesc + "$", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(ongoing);

    if (matcher.find()) {
        newOngoing = matcher.replaceFirst(newIssueDesc);
        cpp.setOngoingConcerns(newOngoing);
        caseManagementCPPDAO.saveCPP(cpp);

        OscarProperties properties = OscarProperties.getInstance();
        if (!Boolean.parseBoolean(properties.getProperty("AbandonOldChart", "false"))) {
            echartDAO.updateEchartOngoing(cpp);
        }
    }

}

From source file:org.kuali.rice.krad.util.KRADUtils.java

/**
 * Strips out common patterns used in cross side scripting.
 *
 * @param value string to strip patterns from
 * @return cleaned string/*from   w w  w. j a va  2 s.c  o  m*/
 */
public static String stripXSSPatterns(String value) {
    if (value == null) {
        return null;
    }

    // Avoid null characters
    value = value.replaceAll("", "");

    // Avoid anything between script tags
    Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
    value = scriptPattern.matcher(value).replaceAll("");

    // Avoid anything in a src='...' type of expression
    scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    value = scriptPattern.matcher(value).replaceAll("");

    scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    value = scriptPattern.matcher(value).replaceAll("");

    // Remove any lonesome </script> tag
    scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
    value = scriptPattern.matcher(value).replaceAll("");

    // Remove any lonesome <script ...> tag
    scriptPattern = Pattern.compile("<script(.*?)>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    value = scriptPattern.matcher(value).replaceAll("");

    // Avoid eval(...) expressions
    scriptPattern = Pattern.compile("eval\\((.*?)\\)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    value = scriptPattern.matcher(value).replaceAll("");

    // Avoid expression(...) expressions
    scriptPattern = Pattern.compile("expression\\((.*?)\\)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    value = scriptPattern.matcher(value).replaceAll("");

    // Avoid javascript:... expressions
    scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
    value = scriptPattern.matcher(value).replaceAll("");

    // Avoid vbscript:... expressions
    scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
    value = scriptPattern.matcher(value).replaceAll("");

    // Avoid onload= expressions
    scriptPattern = Pattern.compile("onload(.*?)=",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    value = scriptPattern.matcher(value).replaceAll("");

    return value;
}

From source file:carnero.cgeo.cgBase.java

public cgCacheWrap parseSearch(cgSearchThread thread, String url, String page, boolean showCaptcha) {
    if (page == null || page.length() == 0) {
        Log.e(cgSettings.tag, "cgeoBase.parseSearch: No page given");
        return null;
    }//from   w ww . j  a  v  a  2  s.c o m

    final cgCacheWrap caches = new cgCacheWrap();
    final ArrayList<String> cids = new ArrayList<String>();
    final ArrayList<String> guids = new ArrayList<String>();
    String recaptchaChallenge = null;
    String recaptchaText = null;

    caches.url = url;

    final Pattern patternCacheType = Pattern.compile(
            "<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^\\.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternGuidAndDisabled = Pattern.compile(
            "<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternTbs = Pattern.compile(
            "<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTbsInside = Pattern.compile(
            "(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternDirection = Pattern.compile(
            "<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternCode = Pattern.compile("\\|[^\\w]*(GC[a-z0-9]+)[^\\|]*\\|",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternId = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\"", Pattern.CASE_INSENSITIVE);
    final Pattern patternFavourite = Pattern.compile(
            "<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTotalCnt = Pattern.compile(
            "<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptcha = Pattern.compile(
            "<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptchaChallenge = Pattern.compile("challenge : '([^']+)'",
            Pattern.CASE_INSENSITIVE);

    caches.viewstate = findViewstate(page, 0);
    caches.viewstate1 = findViewstate(page, 1);

    // recaptcha
    if (showCaptcha == true) {
        try {
            String recaptchaJsParam = null;
            final Matcher matcherRecaptcha = patternRecaptcha.matcher(page);
            while (matcherRecaptcha.find()) {
                if (matcherRecaptcha.groupCount() > 0) {
                    recaptchaJsParam = matcherRecaptcha.group(1);
                }
            }

            if (recaptchaJsParam != null) {
                final String recaptchaJs = request(false, "www.google.com", "/recaptcha/api/challenge", "GET",
                        "k=" + urlencode_rfc3986(recaptchaJsParam.trim()), 0, true).getData();

                if (recaptchaJs != null && recaptchaJs.length() > 0) {
                    final Matcher matcherRecaptchaChallenge = patternRecaptchaChallenge.matcher(recaptchaJs);
                    while (matcherRecaptchaChallenge.find()) {
                        if (matcherRecaptchaChallenge.groupCount() > 0) {
                            recaptchaChallenge = matcherRecaptchaChallenge.group(1).trim();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse recaptcha challenge
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse recaptcha challenge");
        }

        if (thread != null && recaptchaChallenge != null && recaptchaChallenge.length() > 0) {
            thread.setChallenge(recaptchaChallenge);
            thread.notifyNeed();
        }
    }

    int startPos = -1;
    int endPos = -1;

    startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\"");
    if (startPos == -1) {
        Log.e(cgSettings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page");
        return null;
    }

    page = page.substring(startPos); // cut on <table

    startPos = page.indexOf(">");
    endPos = page.indexOf("ctl00_ContentBody_UnitTxt");
    if (startPos == -1 || endPos == -1) {
        Log.e(cgSettings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_UnitTxt\" not found on page");
        return null;
    }

    page = page.substring(startPos + 1, endPos - startPos + 1); // cut between <table> and </table>

    final String[] rows = page.split("<tr class=");
    final int rows_count = rows.length;

    for (int z = 1; z < rows_count; z++) {
        cgCache cache = new cgCache();
        String row = rows[z];

        // check for cache type presence
        if (row.indexOf("images/wpttypes") == -1) {
            continue;
        }

        try {
            final Matcher matcherGuidAndDisabled = patternGuidAndDisabled.matcher(row);

            while (matcherGuidAndDisabled.find()) {
                if (matcherGuidAndDisabled.groupCount() > 0) {
                    guids.add(matcherGuidAndDisabled.group(1));

                    cache.guid = matcherGuidAndDisabled.group(1);
                    if (matcherGuidAndDisabled.group(4) != null) {
                        cache.name = Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString();
                    }
                    if (matcherGuidAndDisabled.group(6) != null) {
                        cache.location = Html.fromHtml(matcherGuidAndDisabled.group(6).trim()).toString();
                    }

                    final String attr = matcherGuidAndDisabled.group(2);
                    if (attr != null) {
                        if (attr.contains("Strike") == true) {
                            cache.disabled = true;
                        } else {
                            cache.disabled = false;
                        }

                        if (attr.contains("OldWarning") == true) {
                            cache.archived = true;
                        } else {
                            cache.archived = false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse GUID and/or Disabled
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse GUID and/or Disabled data");
        }

        if (settings.excludeDisabled == 1 && (cache.disabled == true || cache.archived == true)) {
            // skip disabled and archived caches
            cache = null;
            continue;
        }

        String inventoryPre = null;

        // GC* code
        try {
            final Matcher matcherCode = patternCode.matcher(row);
            while (matcherCode.find()) {
                if (matcherCode.groupCount() > 0) {
                    cache.geocode = matcherCode.group(1).toUpperCase();
                }
            }
        } catch (Exception e) {
            // failed to parse code
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache code");
        }

        // cache type
        try {
            final Matcher matcherCacheType = patternCacheType.matcher(row);
            while (matcherCacheType.find()) {
                if (matcherCacheType.groupCount() > 0) {
                    cache.type = cacheTypes.get(matcherCacheType.group(1).toLowerCase());
                }
            }
        } catch (Exception e) {
            // failed to parse type
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache type");
        }

        // cache direction - image
        try {
            final Matcher matcherDirection = patternDirection.matcher(row);
            while (matcherDirection.find()) {
                if (matcherDirection.groupCount() > 0) {
                    cache.directionImg = matcherDirection.group(1);
                }
            }
        } catch (Exception e) {
            // failed to parse direction image
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache direction image");
        }

        // cache inventory
        try {
            final Matcher matcherTbs = patternTbs.matcher(row);
            while (matcherTbs.find()) {
                if (matcherTbs.groupCount() > 0) {
                    cache.inventoryItems = Integer.parseInt(matcherTbs.group(1));
                    inventoryPre = matcherTbs.group(2);
                }
            }
        } catch (Exception e) {
            // failed to parse inventory
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory (1)");
        }

        if (inventoryPre != null && inventoryPre.trim().length() > 0) {
            try {
                final Matcher matcherTbsInside = patternTbsInside.matcher(inventoryPre);
                while (matcherTbsInside.find()) {
                    if (matcherTbsInside.groupCount() == 2 && matcherTbsInside.group(2) != null) {
                        final String inventoryItem = matcherTbsInside.group(2).toLowerCase();
                        if (inventoryItem.equals("premium member only cache")) {
                            continue;
                        } else {
                            if (cache.inventoryItems <= 0) {
                                cache.inventoryItems = 1;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                // failed to parse cache inventory info
                Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory info");
            }
        }

        // premium cache
        if (row.indexOf("/images/small_profile.gif") != -1) {
            cache.members = true;
        } else {
            cache.members = false;
        }

        // found it
        if (row.indexOf("/images/icons/icon_smile.gif") != -1) {
            cache.found = true;
        } else {
            cache.found = false;
        }

        // own it
        if (row.indexOf("/images/silk/star.png") != -1) {
            cache.own = true;
        } else {
            cache.own = false;
        }

        // id
        try {
            final Matcher matcherId = patternId.matcher(row);
            while (matcherId.find()) {
                if (matcherId.groupCount() > 0) {
                    cache.cacheid = matcherId.group(1);
                    cids.add(cache.cacheid);
                }
            }
        } catch (Exception e) {
            // failed to parse cache id
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache id");
        }

        // favourite count
        try {
            final Matcher matcherFavourite = patternFavourite.matcher(row);
            while (matcherFavourite.find()) {
                if (matcherFavourite.groupCount() > 0) {
                    cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
                }
            }
        } catch (Exception e) {
            // failed to parse favourite count
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse favourite count");
        }

        if (cache.nameSp == null) {
            cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name);
            if (cache.disabled == true || cache.archived == true) { // strike
                cache.nameSp.setSpan(new StrikethroughSpan(), 0, cache.nameSp.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        caches.cacheList.add(cache);
    }

    // total caches found
    try {
        final Matcher matcherTotalCnt = patternTotalCnt.matcher(page);
        while (matcherTotalCnt.find()) {
            if (matcherTotalCnt.groupCount() > 0) {
                if (matcherTotalCnt.group(1) != null) {
                    caches.totalCnt = new Integer(matcherTotalCnt.group(1));
                }
            }
        }
    } catch (Exception e) {
        // failed to parse cache count
        Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache count");
    }

    if (thread != null && recaptchaChallenge != null) {
        if (thread.getText() == null) {
            thread.waitForUser();
        }

        recaptchaText = thread.getText();
    }

    if (cids.size() > 0 && (recaptchaChallenge == null
            || (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0))) {
        Log.i(cgSettings.tag, "Trying to get .loc for " + cids.size() + " caches");

        try {
            // get coordinates for parsed caches
            final String host = "www.geocaching.com";
            final String path = "/seek/nearest.aspx";
            final StringBuilder params = new StringBuilder();
            params.append("__EVENTTARGET=");
            params.append("&");
            params.append("__EVENTARGUMENT=");
            params.append("&");
            params.append("__VIEWSTATE=");
            params.append(urlencode_rfc3986(caches.viewstate));
            if (caches.viewstate1 != null) {
                params.append("&");
                params.append("__VIEWSTATE1=");
                params.append(urlencode_rfc3986(caches.viewstate1));
                params.append("&");
                params.append("__VIEWSTATEFIELDCOUNT=2");
            }

            for (String cid : cids) {
                params.append("&");
                params.append("CID=");
                params.append(urlencode_rfc3986(cid));
            }

            if (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0) {
                params.append("&");
                params.append("recaptcha_challenge_field=");
                params.append(urlencode_rfc3986(recaptchaChallenge));
                params.append("&");
                params.append("recaptcha_response_field=");
                params.append(urlencode_rfc3986(recaptchaText));
            }
            params.append("&");
            params.append("ctl00%24ContentBody%24uxDownloadLoc=Download+Waypoints");

            final String coordinates = request(false, host, path, "POST", params.toString(), 0, true).getData();

            if (coordinates != null && coordinates.length() > 0) {
                if (coordinates.indexOf(
                        "You have not agreed to the license agreement. The license agreement is required before you can start downloading GPX or LOC files from Geocaching.com") > -1) {
                    Log.i(cgSettings.tag,
                            "User has not agreed to the license agreement. Can\'t download .loc file.");

                    caches.error = errorRetrieve.get(-7);

                    return caches;
                }
            }

            if (coordinates != null && coordinates.length() > 0) {
                final HashMap<String, cgCoord> cidCoords = new HashMap<String, cgCoord>();
                final Pattern patternCidCode = Pattern.compile("name id=\"([^\"]+)\"");
                final Pattern patternCidLat = Pattern.compile("lat=\"([^\"]+)\"");
                final Pattern patternCidLon = Pattern.compile("lon=\"([^\"]+)\"");
                // premium only >>
                final Pattern patternCidDif = Pattern.compile("<difficulty>([^<]+)</difficulty>");
                final Pattern patternCidTer = Pattern.compile("<terrain>([^<]+)</terrain>");
                final Pattern patternCidCon = Pattern.compile("<container>([^<]+)</container>");
                // >> premium only

                final String[] points = coordinates.split("<waypoint>");

                // parse coordinates
                for (String point : points) {
                    final cgCoord pointCoord = new cgCoord();
                    final Matcher matcherCidCode = patternCidCode.matcher(point);
                    final Matcher matcherLatCode = patternCidLat.matcher(point);
                    final Matcher matcherLonCode = patternCidLon.matcher(point);
                    final Matcher matcherDifCode = patternCidDif.matcher(point);
                    final Matcher matcherTerCode = patternCidTer.matcher(point);
                    final Matcher matcherConCode = patternCidCon.matcher(point);
                    HashMap<String, Object> tmp = null;

                    if (matcherCidCode.find() == true) {
                        pointCoord.name = matcherCidCode.group(1).trim().toUpperCase();
                    }
                    if (matcherLatCode.find() == true) {
                        tmp = parseCoordinate(matcherLatCode.group(1), "lat");
                        pointCoord.latitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherLonCode.find() == true) {
                        tmp = parseCoordinate(matcherLonCode.group(1), "lon");
                        pointCoord.longitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherDifCode.find() == true) {
                        pointCoord.difficulty = new Float(matcherDifCode.group(1));
                    }
                    if (matcherTerCode.find() == true) {
                        pointCoord.terrain = new Float(matcherTerCode.group(1));
                    }
                    if (matcherConCode.find() == true) {
                        final int size = Integer.parseInt(matcherConCode.group(1));

                        if (size == 1) {
                            pointCoord.size = "not chosen";
                        } else if (size == 2) {
                            pointCoord.size = "micro";
                        } else if (size == 3) {
                            pointCoord.size = "regular";
                        } else if (size == 4) {
                            pointCoord.size = "large";
                        } else if (size == 5) {
                            pointCoord.size = "virtual";
                        } else if (size == 6) {
                            pointCoord.size = "other";
                        } else if (size == 8) {
                            pointCoord.size = "small";
                        } else {
                            pointCoord.size = "unknown";
                        }
                    }

                    cidCoords.put(pointCoord.name, pointCoord);
                }

                Log.i(cgSettings.tag, "Coordinates found in .loc file: " + cidCoords.size());

                // save found cache coordinates
                for (cgCache oneCache : caches.cacheList) {
                    if (cidCoords.containsKey(oneCache.geocode) == true) {
                        cgCoord thisCoords = cidCoords.get(oneCache.geocode);

                        oneCache.latitude = thisCoords.latitude;
                        oneCache.longitude = thisCoords.longitude;
                        oneCache.difficulty = thisCoords.difficulty;
                        oneCache.terrain = thisCoords.terrain;
                        oneCache.size = thisCoords.size;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.parseSearch.CIDs: " + e.toString());
        }
    }

    // get direction images
    cgDirectionImg dirImgDownloader = new cgDirectionImg(settings);
    for (cgCache oneCache : caches.cacheList) {
        if (oneCache.latitude == null && oneCache.longitude == null && oneCache.direction == null
                && oneCache.directionImg != null) {
            dirImgDownloader.getDrawable(oneCache.geocode, oneCache.directionImg);
        }
    }
    dirImgDownloader = null;

    // get ratings
    if (guids.size() > 0) {
        Log.i(cgSettings.tag, "Trying to get ratings for " + cids.size() + " caches");

        try {
            final HashMap<String, cgRating> ratings = getRating(guids, null);

            if (ratings != null) {
                // save found cache coordinates
                for (cgCache oneCache : caches.cacheList) {
                    if (ratings.containsKey(oneCache.guid) == true) {
                        cgRating thisRating = ratings.get(oneCache.guid);

                        oneCache.rating = thisRating.rating;
                        oneCache.votes = thisRating.votes;
                        oneCache.myVote = thisRating.myVote;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.parseSearch.GCvote: " + e.toString());
        }
    }

    return caches;
}

From source file:carnero.cgeo.original.libs.Base.java

public CacheWrap parseSearch(SearchThread thread, String url, String page, boolean showCaptcha) {
    if (page == null || page.length() == 0) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: No page given");
        return null;
    }/*  ww  w .j  av  a  2 s  .  c om*/

    final CacheWrap caches = new CacheWrap();
    final ArrayList<String> cids = new ArrayList<String>();
    final ArrayList<String> guids = new ArrayList<String>();
    String recaptchaChallenge = null;
    String recaptchaText = null;

    caches.url = url;

    final Pattern patternCacheType = Pattern.compile(
            "<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^\\.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternGuidAndDisabled = Pattern.compile(
            "<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternTbs = Pattern.compile(
            "<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTbsInside = Pattern.compile(
            "(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternDirection = Pattern.compile(
            "<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternCode = Pattern.compile("\\|[^\\w]*(GC[a-z0-9]+)[^\\|]*\\|",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternId = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\"", Pattern.CASE_INSENSITIVE);
    final Pattern patternFavourite = Pattern.compile(
            "<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTotalCnt = Pattern.compile(
            "<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptcha = Pattern.compile(
            "<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptchaChallenge = Pattern.compile("challenge : '([^']+)'",
            Pattern.CASE_INSENSITIVE);

    caches.viewstate = findViewstate(page, 0);
    caches.viewstate1 = findViewstate(page, 1);

    // recaptcha
    if (showCaptcha == true) {
        try {
            String recaptchaJsParam = null;
            final Matcher matcherRecaptcha = patternRecaptcha.matcher(page);
            while (matcherRecaptcha.find()) {
                if (matcherRecaptcha.groupCount() > 0) {
                    recaptchaJsParam = matcherRecaptcha.group(1);
                }
            }

            if (recaptchaJsParam != null) {
                final String recaptchaJs = request(false, "www.google.com", "/recaptcha/api/challenge", "GET",
                        "k=" + urlencode_rfc3986(recaptchaJsParam.trim()), 0, true).getData();

                if (recaptchaJs != null && recaptchaJs.length() > 0) {
                    final Matcher matcherRecaptchaChallenge = patternRecaptchaChallenge.matcher(recaptchaJs);
                    while (matcherRecaptchaChallenge.find()) {
                        if (matcherRecaptchaChallenge.groupCount() > 0) {
                            recaptchaChallenge = matcherRecaptchaChallenge.group(1).trim();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse recaptcha challenge
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse recaptcha challenge");
        }

        if (thread != null && recaptchaChallenge != null && recaptchaChallenge.length() > 0) {
            thread.setChallenge(recaptchaChallenge);
            thread.notifyNeed();
        }
    }

    int startPos = -1;
    int endPos = -1;

    startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\"");
    if (startPos == -1) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page");
        return null;
    }

    page = page.substring(startPos); // cut on <table

    startPos = page.indexOf(">");
    endPos = page.indexOf("ctl00_ContentBody_UnitTxt");
    if (startPos == -1 || endPos == -1) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_UnitTxt\" not found on page");
        return null;
    }

    page = page.substring(startPos + 1, endPos - startPos + 1); // cut between <table> and </table>

    final String[] rows = page.split("<tr class=");
    final int rows_count = rows.length;

    for (int z = 1; z < rows_count; z++) {
        Cache cache = new Cache();
        String row = rows[z];

        // check for cache type presence
        if (row.indexOf("images/wpttypes") == -1) {
            continue;
        }

        try {
            final Matcher matcherGuidAndDisabled = patternGuidAndDisabled.matcher(row);

            while (matcherGuidAndDisabled.find()) {
                if (matcherGuidAndDisabled.groupCount() > 0) {
                    guids.add(matcherGuidAndDisabled.group(1));

                    cache.guid = matcherGuidAndDisabled.group(1);
                    if (matcherGuidAndDisabled.group(4) != null) {
                        cache.name = Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString();
                    }
                    if (matcherGuidAndDisabled.group(6) != null) {
                        cache.location = Html.fromHtml(matcherGuidAndDisabled.group(6).trim()).toString();
                    }

                    final String attr = matcherGuidAndDisabled.group(2);
                    if (attr != null) {
                        if (attr.contains("Strike") == true) {
                            cache.disabled = true;
                        } else {
                            cache.disabled = false;
                        }

                        if (attr.contains("OldWarning") == true) {
                            cache.archived = true;
                        } else {
                            cache.archived = false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse GUID and/or Disabled
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse GUID and/or Disabled data");
        }

        if (settings.excludeDisabled == 1 && (cache.disabled == true || cache.archived == true)) {
            // skip disabled and archived caches
            cache = null;
            continue;
        }

        String inventoryPre = null;

        // GC* code
        try {
            final Matcher matcherCode = patternCode.matcher(row);
            while (matcherCode.find()) {
                if (matcherCode.groupCount() > 0) {
                    cache.geocode = matcherCode.group(1).toUpperCase();
                }
            }
        } catch (Exception e) {
            // failed to parse code
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache code");
        }

        // cache type
        try {
            final Matcher matcherCacheType = patternCacheType.matcher(row);
            while (matcherCacheType.find()) {
                if (matcherCacheType.groupCount() > 0) {
                    cache.type = cacheTypes.get(matcherCacheType.group(1).toLowerCase());
                }
            }
        } catch (Exception e) {
            // failed to parse type
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache type");
        }

        // cache direction - image
        try {
            final Matcher matcherDirection = patternDirection.matcher(row);
            while (matcherDirection.find()) {
                if (matcherDirection.groupCount() > 0) {
                    cache.directionImg = matcherDirection.group(1);
                }
            }
        } catch (Exception e) {
            // failed to parse direction image
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache direction image");
        }

        // cache inventory
        try {
            final Matcher matcherTbs = patternTbs.matcher(row);
            while (matcherTbs.find()) {
                if (matcherTbs.groupCount() > 0) {
                    cache.inventoryItems = Integer.parseInt(matcherTbs.group(1));
                    inventoryPre = matcherTbs.group(2);
                }
            }
        } catch (Exception e) {
            // failed to parse inventory
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory (1)");
        }

        if (inventoryPre != null && inventoryPre.trim().length() > 0) {
            try {
                final Matcher matcherTbsInside = patternTbsInside.matcher(inventoryPre);
                while (matcherTbsInside.find()) {
                    if (matcherTbsInside.groupCount() == 2 && matcherTbsInside.group(2) != null) {
                        final String inventoryItem = matcherTbsInside.group(2).toLowerCase();
                        if (inventoryItem.equals("premium member only cache")) {
                            continue;
                        } else {
                            if (cache.inventoryItems <= 0) {
                                cache.inventoryItems = 1;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                // failed to parse cache inventory info
                Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory info");
            }
        }

        // premium cache
        if (row.indexOf("/images/small_profile.gif") != -1) {
            cache.members = true;
        } else {
            cache.members = false;
        }

        // found it
        if (row.indexOf("/images/icons/icon_smile.png") != -1) {
            cache.found = true;
        } else {
            cache.found = false;
        }

        // own it
        if (row.indexOf("/images/silk/star.png") != -1) {
            cache.own = true;
        } else {
            cache.own = false;
        }

        // id
        try {
            final Matcher matcherId = patternId.matcher(row);
            while (matcherId.find()) {
                if (matcherId.groupCount() > 0) {
                    cache.cacheid = matcherId.group(1);
                    cids.add(cache.cacheid);
                }
            }
        } catch (Exception e) {
            // failed to parse cache id
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache id");
        }

        // favourite count
        try {
            final Matcher matcherFavourite = patternFavourite.matcher(row);
            while (matcherFavourite.find()) {
                if (matcherFavourite.groupCount() > 0) {
                    cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
                }
            }
        } catch (Exception e) {
            // failed to parse favourite count
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse favourite count");
        }

        if (cache.nameSp == null) {
            cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name);
            if (cache.disabled == true || cache.archived == true) { // strike
                cache.nameSp.setSpan(new StrikethroughSpan(), 0, cache.nameSp.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        caches.cacheList.add(cache);
    }

    // total caches found
    try {
        final Matcher matcherTotalCnt = patternTotalCnt.matcher(page);
        while (matcherTotalCnt.find()) {
            if (matcherTotalCnt.groupCount() > 0) {
                if (matcherTotalCnt.group(1) != null) {
                    caches.totalCnt = new Integer(matcherTotalCnt.group(1));
                }
            }
        }
    } catch (Exception e) {
        // failed to parse cache count
        Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache count");
    }

    if (thread != null && recaptchaChallenge != null) {
        if (thread.getText() == null) {
            thread.waitForUser();
        }

        recaptchaText = thread.getText();
    }

    if (cids.size() > 0 && (recaptchaChallenge == null
            || (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0))) {
        Log.i(Settings.tag, "Trying to get .loc for " + cids.size() + " caches");

        try {
            // get coordinates for parsed caches
            final String host = "www.geocaching.com";
            final String path = "/seek/nearest.aspx";
            final StringBuilder params = new StringBuilder();
            params.append("__EVENTTARGET=");
            params.append("&");
            params.append("__EVENTARGUMENT=");
            params.append("&");
            params.append("__VIEWSTATE=");
            params.append(urlencode_rfc3986(caches.viewstate));
            if (caches.viewstate1 != null) {
                params.append("&");
                params.append("__VIEWSTATE1=");
                params.append(urlencode_rfc3986(caches.viewstate1));
                params.append("&");
                params.append("__VIEWSTATEFIELDCOUNT=2");
            }

            for (String cid : cids) {
                params.append("&");
                params.append("CID=");
                params.append(urlencode_rfc3986(cid));
            }

            if (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0) {
                params.append("&");
                params.append("recaptcha_challenge_field=");
                params.append(urlencode_rfc3986(recaptchaChallenge));
                params.append("&");
                params.append("recaptcha_response_field=");
                params.append(urlencode_rfc3986(recaptchaText));
            }
            params.append("&");
            params.append("ctl00%24ContentBody%24uxDownloadLoc=Download+Waypoints");

            final String coordinates = request(false, host, path, "POST", params.toString(), 0, true).getData();

            if (coordinates != null && coordinates.length() > 0) {
                if (coordinates.indexOf(
                        "You have not agreed to the license agreement. The license agreement is required before you can start downloading GPX or LOC files from Geocaching.com") > -1) {
                    Log.i(Settings.tag,
                            "User has not agreed to the license agreement. Can\'t download .loc file.");

                    caches.error = errorRetrieve.get(-7);

                    return caches;
                }
            }

            if (coordinates != null && coordinates.length() > 0) {
                final HashMap<String, Coord> cidCoords = new HashMap<String, Coord>();
                final Pattern patternCidCode = Pattern.compile("name id=\"([^\"]+)\"");
                final Pattern patternCidLat = Pattern.compile("lat=\"([^\"]+)\"");
                final Pattern patternCidLon = Pattern.compile("lon=\"([^\"]+)\"");
                // premium only >>
                final Pattern patternCidDif = Pattern.compile("<difficulty>([^<]+)</difficulty>");
                final Pattern patternCidTer = Pattern.compile("<terrain>([^<]+)</terrain>");
                final Pattern patternCidCon = Pattern.compile("<container>([^<]+)</container>");
                // >> premium only

                final String[] points = coordinates.split("<waypoint>");

                // parse coordinates
                for (String point : points) {
                    final Coord pointCoord = new Coord();
                    final Matcher matcherCidCode = patternCidCode.matcher(point);
                    final Matcher matcherLatCode = patternCidLat.matcher(point);
                    final Matcher matcherLonCode = patternCidLon.matcher(point);
                    final Matcher matcherDifCode = patternCidDif.matcher(point);
                    final Matcher matcherTerCode = patternCidTer.matcher(point);
                    final Matcher matcherConCode = patternCidCon.matcher(point);
                    HashMap<String, Object> tmp = null;

                    if (matcherCidCode.find() == true) {
                        pointCoord.name = matcherCidCode.group(1).trim().toUpperCase();
                    }
                    if (matcherLatCode.find() == true) {
                        tmp = parseCoordinate(matcherLatCode.group(1), "lat");
                        pointCoord.latitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherLonCode.find() == true) {
                        tmp = parseCoordinate(matcherLonCode.group(1), "lon");
                        pointCoord.longitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherDifCode.find() == true) {
                        pointCoord.difficulty = new Float(matcherDifCode.group(1));
                    }
                    if (matcherTerCode.find() == true) {
                        pointCoord.terrain = new Float(matcherTerCode.group(1));
                    }
                    if (matcherConCode.find() == true) {
                        final int size = Integer.parseInt(matcherConCode.group(1));

                        if (size == 1) {
                            pointCoord.size = "not chosen";
                        } else if (size == 2) {
                            pointCoord.size = "micro";
                        } else if (size == 3) {
                            pointCoord.size = "regular";
                        } else if (size == 4) {
                            pointCoord.size = "large";
                        } else if (size == 5) {
                            pointCoord.size = "virtual";
                        } else if (size == 6) {
                            pointCoord.size = "other";
                        } else if (size == 8) {
                            pointCoord.size = "small";
                        } else {
                            pointCoord.size = "unknown";
                        }
                    }

                    cidCoords.put(pointCoord.name, pointCoord);
                }

                Log.i(Settings.tag, "Coordinates found in .loc file: " + cidCoords.size());

                // save found cache coordinates
                for (Cache oneCache : caches.cacheList) {
                    if (cidCoords.containsKey(oneCache.geocode) == true) {
                        Coord thisCoords = cidCoords.get(oneCache.geocode);

                        oneCache.latitude = thisCoords.latitude;
                        oneCache.longitude = thisCoords.longitude;
                        oneCache.difficulty = thisCoords.difficulty;
                        oneCache.terrain = thisCoords.terrain;
                        oneCache.size = thisCoords.size;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(Settings.tag, "cgBase.parseSearch.CIDs: " + e.toString());
        }
    }

    // get direction images
    DirectionImg dirImgDownloader = new DirectionImg(settings);
    for (Cache oneCache : caches.cacheList) {
        if (oneCache.latitude == null && oneCache.longitude == null && oneCache.direction == null
                && oneCache.directionImg != null) {
            dirImgDownloader.getDrawable(oneCache.geocode, oneCache.directionImg);
        }
    }
    dirImgDownloader = null;

    return caches;
}

From source file:org.eclipse.birt.report.engine.emitter.docx.writer.BasicComponent.java

public String validHtmlText(String foreignText) {
    Pattern pattern = Pattern.compile(validHtml, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    Matcher matcher = pattern.matcher(foreignText);
    if (matcher.matches()) {
        return foreignText;
    } else//from w w  w  .  jav a 2  s.  c  o  m
        return "<html>" + foreignText + "</html>";
}