Example usage for java.util TreeSet isEmpty

List of usage examples for java.util TreeSet isEmpty

Introduction

In this page you can find the example usage for java.util TreeSet isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

private void garbageCollectJournal(TreeSet<Filename> candidates) {
    // long t = System.currentTimeMillis();
    // first get file list, then live list
    if (SQLPaxosLogger.this.journaler.numOngoingGCs++ > 0)
        log.severe(this + " has " + SQLPaxosLogger.this.journaler.numOngoingGCs + " ongoing log GC tasks");
    this.deleteJournalFiles(candidates, DB_INDEX_JOURNAL ? this.getActiveLogfiles()
            : this.getActiveLogfilesFromCheckpointTable(candidates));
    if (!candidates.isEmpty() && Util.oneIn(COMPACTION_FREQUENCY))
        this.compactLogfiles();
    --SQLPaxosLogger.this.journaler.numOngoingGCs;
    // DelayProfiler.updateDelay("logGC", t);
}

From source file:net.spfbl.http.ServerHTTP.java

private static TreeSet<String> getPostmaterSet(String query) {
    TreeSet<String> emailSet = new TreeSet<String>();
    if (Subnet.isValidIP(query)) {
        String ip = Subnet.normalizeIP(query);
        Reverse reverse = Reverse.get(ip);
        TreeSet<String> reverseSet = reverse.getAddressSet();
        if (!reverseSet.isEmpty()) {
            String hostname = reverseSet.pollFirst();
            do {//  ww w  . j  a v  a2s  .  c  o m
                hostname = Domain.normalizeHostname(hostname, true);
                if (!hostname.endsWith(".arpa")) {
                    String domain;
                    try {
                        domain = Domain.extractDomain(hostname, true);
                    } catch (ProcessException ex) {
                        domain = null;
                    }
                    if (domain != null) {
                        String email = "postmaster@" + domain.substring(1);
                        if (!NoReply.contains(email, true)) {
                            emailSet.add(email);
                        }
                        if (!Generic.containsGeneric(hostname) && SPF.matchHELO(ip, hostname)) {
                            String subdominio = hostname;
                            while (!subdominio.equals(domain)) {
                                email = "postmaster@" + subdominio.substring(1);
                                if (!NoReply.contains(email, true)) {
                                    emailSet.add(email);
                                }
                                int index = subdominio.indexOf('.', 1);
                                subdominio = subdominio.substring(index);
                            }
                        }
                    }
                }
            } while ((hostname = reverseSet.pollFirst()) != null);
        }
    } else if (Domain.isHostname(query)) {
        String hostname = Domain.normalizeHostname(query, false);
        String domain;
        try {
            domain = Domain.extractDomain(hostname, false);
        } catch (ProcessException ex) {
            domain = null;
        }
        if (domain != null) {
            String subdominio = hostname;
            while (subdominio.endsWith(domain)) {
                String email = "postmaster@" + subdominio;
                if (!NoReply.contains(email, true)) {
                    emailSet.add(email);
                }
                int index = subdominio.indexOf('.', 1) + 1;
                subdominio = subdominio.substring(index);
            }
        }
    }
    return emailSet;
}

From source file:net.spfbl.http.ServerHTTP.java

private static void writeBlockFormHTML(Locale locale, StringBuilder builder, TreeSet<String> tokenSet,
        TreeSet<String> selectionSet) throws ProcessException {
    if (!tokenSet.isEmpty()) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            buildText(builder,//ww w . j  a va  2  s .  co  m
                    "Se voc deseja no receber mais mensagens desta origem no futuro, selecione os identificadores que devem ser bloqueados definitivamente:");
        } else {
            buildText(builder,
                    "If you want to stop receiving messages from the source in the future, select identifiers that should definitely be blocked:");
        }
        builder.append("    <form method=\"POST\">\n");
        for (String identifier : tokenSet) {
            builder.append("        <input type=\"checkbox\" name=\"identifier\" value=\"");
            builder.append(identifier);
            if (selectionSet.contains(identifier)) {
                builder.append("\" checked>");
            } else {
                builder.append("\">");
            }
            builder.append(identifier);
            builder.append("<br>\n");
        }
        if (Core.hasRecaptchaKeys()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Para que sua solicitao seja aceita, resolva o desafio reCAPTCHA abaixo.");
            } else {
                buildText(builder, "For your request to be accepted, please solve the reCAPTCHA below.");
            }
        }
        builder.append("      <div id=\"divcaptcha\">\n");
        if (Core.hasRecaptchaKeys()) {
            String recaptchaKeySite = Core.getRecaptchaKeySite();
            String recaptchaKeySecret = Core.getRecaptchaKeySecret();
            ReCaptcha captcha = ReCaptchaFactory.newReCaptcha(recaptchaKeySite, recaptchaKeySecret, false);
            builder.append("      ");
            builder.append(captcha.createRecaptchaHtml(null, null).replace("\r", ""));
            // novo reCAPCHA
            //            builder.append("      <div class=\"g-recaptcha\" data-sitekey=\"");
            //            builder.append(recaptchaKeySite);
            //            builder.append("\"></div>\n");
        }
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("        <input id=\"btngo\" type=\"submit\" value=\"Bloquear\">\n");
        } else {
            builder.append("        <input id=\"btngo\" type=\"submit\" value=\"Block\">\n");
        }
        builder.append("      </div>\n");
        builder.append("    </form>\n");
    }
}

From source file:net.spfbl.http.ServerHTTP.java

private static String getControlPanel(Locale locale, Query query, long time) {
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(time);/*ww w  .j a v  a2  s.  co m*/
    StringBuilder builder = new StringBuilder();
    //        builder.append("<!DOCTYPE html>\n");
    builder.append("<html lang=\"");
    builder.append(locale.getLanguage());
    builder.append("\">\n");
    builder.append("  <head>\n");
    builder.append("    <meta charset=\"UTF-8\">\n");
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        builder.append("    <title>Painel de controle do SPFBL</title>\n");
    } else {
        builder.append("    <title>SPFBL control panel</title>\n");
    }
    // Styled page.
    builder.append("    <style type=\"text/css\">\n");
    builder.append("      body {");
    builder.append("        background: #b4b9d2;\n");
    builder.append("      }\n");
    builder.append("      .button {\n");
    builder.append("          background-color: #4CAF50;\n");
    builder.append("          border: none;\n");
    builder.append("          color: white;\n");
    builder.append("          padding: 16px 32px;\n");
    builder.append("          text-align: center;\n");
    builder.append("          text-decoration: none;\n");
    builder.append("          display: inline-block;\n");
    builder.append("          font-size: 16px;\n");
    builder.append("          margin: 4px 2px;\n");
    builder.append("          -webkit-transition-duration: 0.4s;\n");
    builder.append("          transition-duration: 0.4s;\n");
    builder.append("          cursor: pointer;\n");
    builder.append("      }\n");
    builder.append("      .white {\n");
    builder.append("          background-color: white; \n");
    builder.append("          color: black; \n");
    builder.append("          border: 2px solid #4CAF50;\n");
    builder.append("          font-weight: bold;\n");
    builder.append("      }\n");
    builder.append("      .white:hover {\n");
    builder.append("          background-color: #4CAF50;\n");
    builder.append("          color: white;\n");
    builder.append("      }\n");
    builder.append("      .block {\n");
    builder.append("          background-color: white; \n");
    builder.append("          color: black; \n");
    builder.append("          border: 2px solid #f44336;\n");
    builder.append("          font-weight: bold;\n");
    builder.append("      }\n");
    builder.append("      .block:hover {\n");
    builder.append("          background-color: #f44336;\n");
    builder.append("          color: white;\n");
    builder.append("      }\n");
    builder.append("      .recipient {\n");
    builder.append("          background-color: white; \n");
    builder.append("          color: black; \n");
    builder.append("          border: 2px solid #555555;\n");
    builder.append("          font-weight: bold;\n");
    builder.append("      }\n");
    builder.append("      .recipient:hover {\n");
    builder.append("          background-color: #555555;\n");
    builder.append("          color: white;\n");
    builder.append("      }\n");
    builder.append("    </style>\n");
    builder.append("  </head>\n");
    // Body.
    builder.append("  <body>\n");
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        builder.append("    <b>Recepo:</b> ");
    } else {
        builder.append("    <b>Reception:</b> ");
    }
    builder.append(dateFormat.format(calendar.getTime()));
    builder.append("<br>\n");
    String sender = query.getSenderSimplified(false, false);
    if (sender == null) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <b>Remetente:</b> MAILER-DAEMON");
        } else {
            builder.append("    <b>Sender:</b> MAILER-DAEMON");
        }
    } else if (query.getQualifierName().equals("PASS")) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <b>Remetente autntico:</b> ");
        } else {
            builder.append("    <b>Genuine sender:</b> ");
        }
        builder.append(sender);
    } else if (query.getQualifierName().equals("FAIL")) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <b>Remetente falso:</b> ");
        } else {
            builder.append("    <b>False sender:</b> ");
        }
        builder.append(sender);
    } else {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <b>Remetente suspeito:</b> ");
        } else {
            builder.append("    <b>Suspect sender:</b> ");
        }
        builder.append(sender);
    }
    builder.append("<br>\n");
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        builder.append("    <b>Recebe por:</b> ");
    } else {
        builder.append("    <b>Receives for:</b> ");
    }
    String validator = query.getValidator(true);
    Situation situationWhite = query.getSenderWhiteSituation();
    Situation situationBlock = query.getSenderBlockSituation();
    try {
        TreeSet<String> mxDomainSet = query.getSenderMXDomainSet();
        if (mxDomainSet.isEmpty()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("nenhum sistema");
            } else {
                builder.append("no system");
            }
        } else {
            builder.append(mxDomainSet);
        }
    } catch (NameNotFoundException ex) {
        validator = null;
        situationWhite = query.getOriginWhiteSituation();
        situationBlock = query.getOriginBlockSituation();
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("domnio inexistente");
        } else {
            builder.append("non-existent domain");
        }
    } catch (NamingException ex) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("erro ao tentar consultar");
        } else {
            builder.append("error when trying to query");
        }
    }
    builder.append("<br>\n");
    URL unsubscribe = query.getUnsubscribeURL();
    if (unsubscribe == null) {
        builder.append("    <br>\n");
    } else {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("     <b>Cancelar inscrio:</b> ");
        } else {
            builder.append("     <b>List unsubscribe:</b> ");
        }
        builder.append("<a target=\"_blank\" href=\"");
        builder.append(unsubscribe);
        builder.append("\">");
        builder.append(unsubscribe.getHost());
        builder.append(unsubscribe.getPath());
        builder.append("</a><br>\n");
    }
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        builder.append("    <b>Politica vigente:</b> ");
    } else {
        builder.append("    <b>Current policy:</b> ");
    }
    String recipient = query.getRecipient();
    Long trapTime = query.getTrapTime();
    boolean blocked = false;
    if (trapTime == null && situationWhite == Situation.SAME) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria na mesma situao, exceto malware");
        } else {
            builder.append("priority delivery of ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" in the same situation, except malware");
        }
    } else if (trapTime == null && situationWhite == Situation.AUTHENTIC) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria de ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" quando comprovadamente autntico, exceto malware");
        } else {
            builder.append("priority delivery of ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" when proven authentic, except malware");
        }
        if (query.isBlock()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append(", porm bloqueado para outras situaes");
            } else {
                builder.append(", however blocked to other situations");
            }
        }
    } else if (trapTime == null && situationWhite == Situation.ZONE) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria de ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" quando disparado por ");
        } else {
            builder.append("priority delivery of ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" when shot by ");
        }
        builder.append(validator);
        if (query.isBlock()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append(", porm bloqueado para outras situaes");
            } else {
                builder.append(", however blocked to other situations");
            }
        }
    } else if (trapTime == null && situationWhite == Situation.IP) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria de ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" when shot by IP ");
        } else {
            builder.append("priority delivery of ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" when coming from the IP ");
        }
        builder.append(validator);
        if (query.isBlock()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append(", porm bloqueado para outras situaes");
            } else {
                builder.append(", however blocked to other situations");
            }
        }
    } else if (trapTime == null && situationWhite == Situation.ORIGIN) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria pela mesma origem");
        } else {
            builder.append("priority delivery the same origin");
        }
    } else if (situationBlock == Situation.DOMAIN) {
        blocked = true;
        String domain = query.getSenderSimplified(true, false);
        if (domain == null) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("bloquear na mesma situao");
            } else {
                builder.append("block in the same situation");
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("bloquear ");
                builder.append(domain);
                builder.append(" em qualquer situao");
            } else {
                builder.append("block ");
                builder.append(domain);
                builder.append(" in any situation");
            }
        }
    } else if (situationBlock == Situation.ALL) {
        blocked = true;
        String domain = query.getOriginDomain(false);
        if (domain == null) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("bloquear na mesma situao");
            } else {
                builder.append("block in the same situation");
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("bloquear ");
                builder.append(domain);
                builder.append(" em qualquer situao");
            } else {
                builder.append("block ");
                builder.append(domain);
                builder.append(" in any situation");
            }
        }
    } else if (situationBlock == Situation.SAME) {
        blocked = true;
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("bloquear na mesma situao");
        } else {
            builder.append("block in the same situation");
        }
    } else if ((situationBlock == Situation.ZONE || situationBlock == Situation.IP)
            && !query.getQualifierName().equals("PASS")) {
        blocked = true;
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("bloquear ");
            builder.append(query.getSenderDomain(false));
            builder.append(" quando no for autntico");
        } else {
            builder.append("block ");
            builder.append(query.getSenderDomain(false));
            builder.append(" when not authentic");
        }
    } else if (situationBlock == Situation.ORIGIN) {
        blocked = true;
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("bloquear quando disparado pela mesma origem");
        } else {
            builder.append("block when shot by the same source");
        }
    } else if (query.isFail()) {
        blocked = true;
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("rejeitar entrega por falsificao");
        } else {
            builder.append("reject delivery of forgery");
        }
    } else if (trapTime != null) {
        if (System.currentTimeMillis() > trapTime) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("descartar mensagem por armadilha");
            } else {
                builder.append("discard message by spamtrap");
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("rejeitar entrega por destinatrio inexistente");
            } else {
                builder.append("reject delivery by inexistent recipient");
            }
        }
    } else if (query.hasTokenRed() || query.hasClusterRed()) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("marcar como suspeita e entregar, sem considerar o contedo");
        } else {
            builder.append("flag as suspected and deliver, regardless of content");
        }
    } else if (query.isSoftfail() || query.hasYellow()) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("atrasar entrega na mesma situao, sem considerar o contedo");
        } else {
            builder.append("delay delivery in the same situation, regardless of content");
        }
    } else {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("aceitar entrega na mesma situao, sem considerar o contedo");
        } else {
            builder.append("accept delivery in the same situation, regardless of content");
        }
    }
    builder.append(".<br>\n");
    builder.append("    <form method=\"POST\">\n");
    if (validator == null) {
        if (situationWhite != Situation.ORIGIN) {
            builder.append(
                    "      <button type=\"submit\" class=\"white\" name=\"POLICY\" value=\"WHITE_ORIGIN\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria quando for da mesma origem\n");
            } else {
                builder.append("Priority delivery when the same origin\n");
            }
            builder.append("</button>\n");
        }
        if (situationWhite != Situation.NONE || situationBlock != Situation.ALL) {
            if (situationBlock != Situation.ORIGIN) {
                builder.append(
                        "      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_ORIGIN\">");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("Bloquear se for da mesma origem");
                } else {
                    builder.append("Block if the same origin");
                }
                builder.append("</button>\n");
            }
            String domain = query.getOriginDomain(false);
            if (domain != null) {
                builder.append(
                        "      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_ALL\">");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("Bloquear ");
                    builder.append(domain);
                    builder.append(" em qualquer situao");
                } else {
                    builder.append("Block ");
                    builder.append(domain);
                    builder.append(" in any situation");
                }
                builder.append("</button>\n");
            }
        }
    } else if (validator.equals("PASS")) {
        if (situationWhite != Situation.AUTHENTIC) {
            builder.append(
                    "      <button type=\"submit\" class=\"white\" name=\"POLICY\" value=\"WHITE_AUTHENTIC\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria quando comprovadamente autntico\n");
            } else {
                builder.append("Priority delivery when proven authentic\n");
            }
            builder.append("</button>\n");
        }
    } else if (Subnet.isValidIP(validator)) {
        if (situationWhite != Situation.IP) {
            builder.append("      <button type=\"submit\" class=\"white\" name=\"POLICY\" value=\"WHITE_IP\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria quando disparado pelo IP ");
            } else {
                builder.append("Priority delivery when shot by IP ");
            }
            builder.append(validator);
            builder.append("</button>\n");
        }
        if (situationBlock != Situation.IP && situationBlock != Situation.DOMAIN) {
            builder.append("      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_IP\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Bloquear ");
                builder.append(query.getSenderDomain(false));
                builder.append(" quando no for autntico");
            } else {
                builder.append("Block ");
                builder.append(query.getSenderDomain(false));
                builder.append(" when not authentic");
            }
            builder.append("</button>\n");
        }
    } else if (Domain.isHostname(validator)) {
        if (situationWhite != Situation.ZONE) {
            builder.append(
                    "      <button type=\"submit\" class=\"white\" name=\"POLICY\" value=\"WHITE_ZONE\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria quando disparado por ");
            } else {
                builder.append("Priority delivery when shot by ");
            }
            builder.append(validator);
            builder.append("</button>\n");
        }
        if (situationBlock != Situation.ZONE && situationBlock != Situation.DOMAIN) {
            builder.append(
                    "      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_ZONE\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Bloquear ");
                builder.append(query.getSenderDomain(false));
                builder.append(" quando no for autntico");
            } else {
                builder.append("Block ");
                builder.append(query.getSenderDomain(false));
                builder.append(" when not authentic");
            }
            builder.append("</button>\n");
        }
    }
    if (situationBlock != Situation.DOMAIN && validator != null) {
        builder.append("      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_DOMAIN\">");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("Bloquear ");
            builder.append(query.getSenderSimplified(true, false));
            builder.append(" em qualquer situao");
        } else {
            builder.append("Block ");
            builder.append(query.getSenderSimplified(true, false));
            builder.append(" in any situation");
        }
        builder.append("</button>\n");
    }
    if (!blocked && recipient != null && trapTime != null && query.getUser().isPostmaster()) {
        builder.append(
                "      <button type=\"submit\" class=\"recipient\" name=\"POLICY\" value=\"WHITE_RECIPIENT\">");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("Tornar ");
            builder.append(recipient);
            builder.append(" existente");
        } else {
            builder.append("Make ");
            builder.append(recipient);
            builder.append(" existent");
        }
        builder.append("</button>\n");
    }
    builder.append("    </form>\n");
    builder.append("  </body>\n");
    builder.append("</html>\n");
    return builder.toString();
}

From source file:net.spfbl.http.ServerHTTP.java

private static String getDNSBLHTML(Locale locale, Client client, final String query, String message) {
    StringBuilder builder = new StringBuilder();
    boolean isSLAAC = SubnetIPv6.isSLAAC(query) && !Subnet.isReservedIP(query);
    Boolean isOpenSMTP = openSMTP.get(query);
    builder.append("<!DOCTYPE html>\n");
    builder.append("<html lang=\"");
    builder.append(locale.getLanguage());
    builder.append("\">\n");
    String title;/*from   w  ww . j a  v a  2 s .  c o  m*/
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        title = "Pgina de checagem DNSBL";
    } else {
        title = "DNSBL check page";
    }
    if (isSLAAC && isOpenSMTP == null) {
        if (openSMTP.containsKey(query)) {
            buildHead(builder, title, Core.getURL(locale, query), 5);
        } else {
            buildHead(builder, title, Core.getURL(locale, query), 10);
            openSMTP.put(query, null);
            new Thread() {
                @Override
                public void run() {
                    Thread.currentThread().setName("BCKGROUND");
                    openSMTP.put(query, Analise.isOpenSMTP(query, 30000));
                }
            }.start();
        }
    } else {
        buildHead(builder, title);
    }
    builder.append("  <body>\n");
    builder.append("    <div id=\"container\">\n");
    builder.append(
            "      <iframe data-aa='455818' src='//ad.a-ads.com/455818?size=468x60' scrolling='no' style='width:468px; height:60px; border:0px; padding:0;overflow:hidden' allowtransparency='true'></iframe>");
    buildMessage(builder, message);
    TreeSet<String> emailSet = new TreeSet<String>();
    if (Subnet.isValidIP(query)) {
        String ip = Subnet.normalizeIP(query);
        if (Subnet.isReservedIP(ip)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder, "Este  um IP reservado e por este motivo no  abordado nesta lista.");
            } else {
                buildText(builder, "This is a reserved IP and for this reason is not addressed in this list.");
            }
        } else if (isSLAAC && isOpenSMTP == null) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este IP contm sinalizao de autoconfigurao de endereo de rede (SLAAC).");
                buildText(builder, "Estamos verificando se existe servio SMTP neste IP. Aguarde...");
            } else {
                buildText(builder, "This IP contains network address autoconfiguration flag (SLAAC).");
                buildText(builder, "We are checking if there is SMTP service on this IP. Wait...");
            }
        } else if (isSLAAC && !isOpenSMTP) {
            openSMTP.remove(query);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este IP contm sinalizao de autoconfigurao de endereo de rede (SLAAC) mas no foi possvel verificar se existe um servio de e-mail vlido nele.");
                buildText(builder,
                        "Se este IP est sendo usado por um servidor de e-mail legtimo, abra a porta 25 para que possamos verificar que existe um servio SMTP nele.");
            } else {
                buildText(builder,
                        "This IP contains network address autoconfiguration flag (SLAAC) but it was not possible to verify that there is a valid email service on it.");
                buildText(builder,
                        "If this IP is being used by genuine email server, open port 25 so we can check that there is a SMTP service on it.");
            }
        } else {
            openSMTP.remove(query);
            boolean generic = false;
            Reverse reverse = Reverse.get(ip, true);
            TreeSet<String> reverseSet = reverse.getAddressSet();
            if (reverseSet.isEmpty()) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder,
                            "Nenhum <a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> foi encontrado.");
                } else {
                    buildText(builder,
                            "No <a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> was found.");
                }
            } else {
                if (reverseSet.size() == 1) {
                    if (locale.getLanguage().toLowerCase().equals("pt")) {
                        buildText(builder,
                                "Este  o <a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> encontrado:");
                    } else {
                        buildText(builder,
                                "This is the <a target=\"_blank\" href=\"http://spfbl.net/en/rdns/\">rDNS</a> found:");
                    }
                } else {
                    if (locale.getLanguage().toLowerCase().equals("pt")) {
                        buildText(builder,
                                "Estes so os <a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> encontrados:");
                    } else {
                        buildText(builder,
                                "These are the <a target=\"_blank\" href=\"http://spfbl.net/en/rdns/\">rDNS</a> found:");
                    }
                }
                Client abuseClient = Client.getByIP(ip);
                String abuseEmail = abuseClient == null || abuseClient.hasPermission(NONE) ? null
                        : abuseClient.getEmail();
                String clientEmail = client == null || client.hasPermission(NONE) ? null : client.getEmail();
                builder.append("        <ul>\n");
                String hostname = reverseSet.pollFirst();
                do {
                    hostname = Domain.normalizeHostname(hostname, false);
                    builder.append("          <li>&lt;");
                    builder.append(hostname);
                    builder.append("&gt; ");
                    if (Generic.containsDynamic(hostname)) {
                        if (locale.getLanguage().toLowerCase().equals("pt")) {
                            builder.append("<a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> ");
                            builder.append(
                                    "de <a target=\"_blank\" href=\"http://spfbl.net/dynamic/\">IP dinmico</a>.</li>\n");
                        } else {
                            builder.append(
                                    "<a target=\"_blank\" href=\"http://spfbl.net/en/dynamic/\">dynamic IP</a> ");
                            builder.append(
                                    "<a target=\"_blank\" href=\"http://spfbl.net/en/rdns/\">rDNS</a>.</li>\n");
                        }
                    } else if (SPF.matchHELO(ip, hostname, true)) {
                        String domain;
                        try {
                            domain = Domain.extractDomain(hostname, false);
                        } catch (ProcessException ex) {
                            domain = null;
                        }
                        if (domain == null) {
                            if (locale.getLanguage().toLowerCase().equals("pt")) {
                                builder.append("domnio reservado.</li>\n");
                            } else {
                                builder.append("reserved domain.</li>\n");
                            }
                        } else if (hostname.endsWith(".arpa")) {
                            if (locale.getLanguage().toLowerCase().equals("pt")) {
                                builder.append("domnio reservado.</li>\n");
                            } else {
                                builder.append("reserved domain.</li>\n");
                            }
                        } else if (Generic.containsGeneric(domain)) {
                            if (abuseEmail != null) {
                                emailSet.add(abuseEmail);
                            }
                            if (locale.getLanguage().toLowerCase().equals("pt")) {
                                builder.append("domnio genrico.</li>\n");
                            } else {
                                builder.append("generic domain.</li>\n");
                            }
                        } else if (Generic.containsGeneric(hostname)) {
                            emailSet.add("postmaster@" + domain);
                            if (abuseEmail != null) {
                                emailSet.add(abuseEmail);
                            }
                            if (clientEmail != null) {
                                emailSet.add(clientEmail);
                            }
                            if (locale.getLanguage().toLowerCase().equals("pt")) {
                                builder.append(
                                        "<a target=\"_blank\" href=\"http://spfbl.net/generic/\">rDNS genrico</a>.</li>\n");
                            } else {
                                builder.append(
                                        "<a target=\"_blank\" href=\"http://spfbl.net/en/generic/\">generic rDNS</a>.</li>\n");
                            }
                        } else {
                            int loop = 0;
                            String subdominio = hostname;
                            while (loop++ < 32 && subdominio.endsWith(domain)) {
                                emailSet.add("postmaster@" + subdominio);
                                int index = subdominio.indexOf('.', 1) + 1;
                                subdominio = subdominio.substring(index);
                            }
                            if (abuseEmail != null) {
                                emailSet.add(abuseEmail);
                            }
                            if (clientEmail != null) {
                                emailSet.add(clientEmail);
                            }
                            if (locale.getLanguage().toLowerCase().equals("pt")) {
                                builder.append(
                                        "<a target=\"_blank\" href=\"http://spfbl.net/fcrdns/\">FCrDNS</a> vlido.</li>\n");
                            } else {
                                builder.append(
                                        "valid <a target=\"_blank\" href=\"http://spfbl.net/en/fcrdns/\">FCrDNS</a>.</li>\n");
                            }
                        }
                    } else {
                        if (abuseEmail != null) {
                            emailSet.add(abuseEmail);
                        }
                        if (locale.getLanguage().toLowerCase().equals("pt")) {
                            builder.append(
                                    "<a target=\"_blank\" href=\"http://spfbl.net/fcrdns/\">FCrDNS</a> invlido.</li>\n");
                        } else {
                            builder.append(
                                    "invalid <a target=\"_blank\" href=\"http://spfbl.net/en/fcrdns/\">FCrDNS</a>.</li>\n");
                        }
                    }
                } while ((hostname = reverseSet.pollFirst()) != null);
                builder.append("        </ul>\n");
            }
            Distribution distribution;
            if ((distribution = SPF.getDistribution(ip, true)).isNotGreen(ip)) {
                float probability = distribution.getSpamProbability(ip);
                boolean blocked = Block.containsCIDR(ip);
                if (blocked || distribution.isRed(ip)) {
                    if (locale.getLanguage().toLowerCase().equals("pt")) {
                        buildText(builder,
                                "Este IP " + (blocked ? "foi bloqueado" : "est listado")
                                        + " por m reputao com " + Core.PERCENT_FORMAT.format(probability)
                                        + " de pontos negativos.");
                        buildText(builder,
                                "Para que este IP possa ser removido desta lista,  necessrio que o MTA de origem reduza o volume de envios para os destinatrios com <a target=\"_blank\" href=\"http://spfbl.net/feedback/\">prefixo de rejeio SPFBL</a> na camada SMTP.");
                    } else {
                        buildText(builder,
                                "This IP " + (blocked ? "was blocked" : "is listed") + " by poor reputation in "
                                        + Core.PERCENT_FORMAT.format(probability) + " of negative points.");
                        buildText(builder,
                                "In order for this IP to be removed from this list, it is necessary that the source MTA reduce the sending volume for the recipients with <a target=\"_blank\" href=\"http://spfbl.net/en/feedback/\">SPFBL rejection prefix</a> at SMTP layer.");
                    }
                } else {
                    if (locale.getLanguage().toLowerCase().equals("pt")) {
                        buildText(builder,
                                "Este IP no est listado neste sistema porm sua reputao est com "
                                        + Core.PERCENT_FORMAT.format(probability) + "de pontos negativos.");
                        buildText(builder,
                                "Se esta reputao tiver aumento significativo na quantidade de pontos negativos, este IP ser automaticamente listado neste sistema.");
                        buildText(builder,
                                "Para evitar que isto ocorra, reduza os envios com <a target=\"_blank\" href=\"http://spfbl.net/feedback/\">prefixo de rejeio SPFBL</a>.");
                    } else {
                        buildText(builder, "This IP is not listed in this system but its reputation is with "
                                + Core.PERCENT_FORMAT.format(probability) + " of negative points.");
                        buildText(builder,
                                "If this reputation have significant increase in the number of negative points, this IP will automatically be listed in the system.");
                        buildText(builder,
                                "To prevent this from occurring, reduce sending with <a target=\"_blank\" href=\"http://spfbl.net/en/feedback/\">SPFBL rejection prefix</a>.");
                    }
                }
            } else if (emailSet.isEmpty()) {
                boolean good = SPF.isGood(ip);
                boolean blocked = Block.containsCIDR(ip);
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    if (blocked) {
                        buildText(builder,
                                "Este IP foi bloqueado por no ter <a target=\"_blank\" href=\"http://spfbl.net/fcrdns/\">FCrDNS</a> vlido.");
                    } else if (good) {
                        buildText(builder,
                                "Este IP est com reputao muito boa, porm no tem um <a target=\"_blank\" href=\"http://spfbl.net/fcrdns/\">FCrDNS</a> vlido.");
                    } else {
                        buildText(builder,
                                "Este IP no est bloqueado porm no tem um <a target=\"_blank\" href=\"http://spfbl.net/fcrdns/\">FCrDNS</a> vlido.");
                    }
                    if (generic) {
                        buildText(builder,
                                "No sero aceitos <a target=\"_blank\" href=\"http://spfbl.net/generic/\">rDNS genricos</a>.");
                    }
                    buildText(builder,
                            "Cadastre um <a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> vlido para este IP, que aponte para o mesmo IP.");
                    if (blocked) {
                        buildText(builder,
                                "O <a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> deve estar sob seu prprio domnio para que a liberao seja efetivada.");
                    } else {
                        buildText(builder,
                                "Qualquer IP com <a target=\"_blank\" href=\"http://spfbl.net/fcrdns/\">FCrDNS</a> invlido pode ser bloqueado a qualquer momento.");
                    }
                } else {
                    if (blocked) {
                        buildText(builder,
                                "This IP has been blocked because have none valid <a target=\"_blank\" href=\"http://spfbl.net/en/fcrdns/\">FCrDNS</a>.");
                    } else if (good) {
                        buildText(builder,
                                "This IP has a very good reputation, but does not have a <a target=\"_blank\" href=\"http://spfbl.net/fcrdns/\">FCrDNS</a> vlido.");
                    } else {
                        buildText(builder,
                                "This IP isn't blocked but have none valid <a target=\"_blank\" href=\"http://spfbl.net/en/fcrdns/\">FCrDNS</a>.");
                    }
                    if (generic) {
                        buildText(builder,
                                "<a target=\"_blank\" href=\"http://spfbl.net/en/generic/\"Generic rDNS</a> will not be accepted.");
                    }
                    buildText(builder,
                            "Register a valid <a target=\"_blank\" href=\"http://spfbl.net/en/rdns/\">rDNS</a> for this IP, which points to the same IP.");
                    if (blocked) {
                        buildText(builder,
                                "The <a target=\"_blank\" href=\"http://spfbl.net/en/rdns/\">rDNS</a> must be registered under your own domain for us to be able to delist your system.");
                    } else {
                        buildText(builder,
                                "Any IP with invalid <a target=\"_blank\" href=\"http://spfbl.net/en/fcrdns/\">FCrDNS</a> can be blocked at any time.");
                    }
                }
            } else if (Block.containsCIDR(ip)) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder,
                            "Este IP foi bloqueado, porm a reputao dele no est mais ruim.");
                } else {
                    buildText(builder, "This IP has been blocked, but it's reputation is not bad anymore.");
                }
                builder.append("      <hr>\n");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder,
                            "Para que a chave de desbloqueio possa ser enviada, selecione o endereo de e-mail do responsvel pelo IP:");
                } else {
                    buildText(builder,
                            "For the delist key can be sent, select the e-mail address responsible for this IP:");
                }
                builder.append("      <form method=\"POST\">\n");
                builder.append("        <ul>\n");
                int permittedCount = 0;
                for (String email : emailSet) {
                    if (Domain.isValidEmail(email)) {
                        if (!Trap.contaisAnything(email)) {
                            if (!NoReply.contains(email, false)) {
                                permittedCount++;
                            }
                        }
                    }
                }
                boolean permittedChecked = false;
                String email = emailSet.pollFirst();
                do {
                    if (!Domain.isValidEmail(email)) {
                        builder.append("          <input type=\"radio\" name=\"identifier\" value=\"");
                        builder.append(email);
                        builder.append("\" disabled>");
                        builder.append("&lt;");
                        builder.append(email);
                        builder.append("&gt; ");
                        if (locale.getLanguage().toLowerCase().equals("pt")) {
                            builder.append("invlido.<br>\n");
                        } else {
                            builder.append("invalid.<br>\n");
                        }
                    } else if (Trap.contaisAnything(email)) {
                        builder.append("          <input type=\"radio\" name=\"identifier\" value=\"");
                        builder.append(email);
                        builder.append("\" disabled>");
                        builder.append("&lt;");
                        builder.append(email);
                        builder.append("&gt; ");
                        if (locale.getLanguage().toLowerCase().equals("pt")) {
                            builder.append("inexistente.</li><br>\n");
                        } else {
                            builder.append("non-existent.</li><br>\n");
                        }
                    } else if (NoReply.contains(email, false)) {
                        builder.append("          <input type=\"radio\" name=\"identifier\" value=\"");
                        builder.append(email);
                        builder.append("\" disabled>");
                        builder.append("&lt;");
                        builder.append(email);
                        builder.append("&gt; ");
                        if (locale.getLanguage().toLowerCase().equals("pt")) {
                            builder.append("no permitido.<br>\n");
                        } else {
                            builder.append("not permitted.<br>\n");
                        }
                    } else {
                        builder.append("          <input type=\"radio\" name=\"identifier\" ");
                        builder.append(
                                "onclick=\"document.getElementById('btngo').disabled = false;\" value=\"");
                        builder.append(email);
                        if (permittedChecked) {
                            builder.append("\">");
                        } else if (permittedCount == 1) {
                            builder.append("\" checked>");
                            permittedChecked = true;
                        } else {
                            builder.append("\">");
                        }
                        builder.append("&lt;");
                        builder.append(email);
                        builder.append("&gt; ");
                        if (locale.getLanguage().toLowerCase().equals("pt")) {
                            builder.append("permitido.<br>\n");
                        } else {
                            builder.append("permitted.<br>\n");
                        }
                    }
                } while ((email = emailSet.pollFirst()) != null);
                builder.append("        </ul>\n");
                if (permittedCount == 0) {
                    if (locale.getLanguage().toLowerCase().equals("pt")) {
                        buildText(builder, "Nenhum e-mail do responsvel pelo IP  permitido neste sistema.");
                    } else {
                        buildText(builder,
                                "None of the responsible for IP has e-mail permitted under this system.");
                    }
                } else {
                    if (locale.getLanguage().toLowerCase().equals("pt")) {
                        buildText(builder,
                                "O <a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> do IP deve estar sob seu prprio domnio. No aceitamos <a target=\"_blank\" href=\"http://spfbl.net/rdns/\">rDNS</a> com domnios de terceiros.");
                    } else {
                        buildText(builder,
                                "The <a target=\"_blank\" href=\"http://spfbl.net/en/rdns/\">rDNS</a> must be registered under your own domain. We do not accept <a target=\"_blank\" href=\"http://spfbl.net/en/rdns/\">rDNS</a> with third-party domains.");
                    }
                    builder.append("        <div id=\"divcaptcha\">\n");
                    if (Core.hasRecaptchaKeys()) {
                        String recaptchaKeySite = Core.getRecaptchaKeySite();
                        String recaptchaKeySecret = Core.getRecaptchaKeySecret();
                        ReCaptcha captcha = ReCaptchaFactory.newReCaptcha(recaptchaKeySite, recaptchaKeySecret,
                                false);
                        builder.append("        ");
                        builder.append(captcha.createRecaptchaHtml(null, null).replace("\r", ""));
                        // novo reCAPCHA
                        //            builder.append("      <div class=\"g-recaptcha\" data-sitekey=\"");
                        //            builder.append(recaptchaKeySite);
                        //            builder.append("\"></div>\n");
                    }
                    if (locale.getLanguage().toLowerCase().equals("pt")) {
                        builder.append(
                                "          <input id=\"btngo\" type=\"submit\" value=\"Solicitar chave de delist\"");
                    } else {
                        builder.append(
                                "          <input id=\"btngo\" type=\"submit\" value=\"Request delist key\"");
                    }
                    if (permittedCount == 1) {
                        builder.append(">\n");
                    } else {
                        builder.append(" disabled>\n");
                    }
                    builder.append("        </div>\n");
                    builder.append("      </form>\n");
                }
            } else if (SPF.isGood(ip)) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder,
                            "Este IP est com reputao extremamente boa e por isso foi colocado em lista branca.");
                } else {
                    buildText(builder,
                            "This IP is extremely good reputation and therefore has been whitelisted.");
                }
            } else if (Ignore.containsCIDR(ip)) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder,
                            "Este IP est marcado como servio essencial e por isso foi colocado em lista branca.");
                } else {
                    buildText(builder,
                            "This IP is marked as an essential service and therefore has been whitelisted.");
                }
            } else if (White.containsIP(ip)) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder,
                            "Este IP est marcado como servio de mensagem estritamente corporativo e por isso foi colocado em lista branca.");
                    if (Core.hasAbuseEmail()) {
                        buildText(builder,
                                "Se voc tiver recebido alguma mensagem promocional deste IP, sem prvia autorizao, faa uma denuncia para "
                                        + Core.getAbuseEmail() + ".");
                    }
                } else {
                    buildText(builder,
                            "This IP is marked as strictly corporate message service and therefore has been whitelisted.");
                    if (Core.hasAbuseEmail()) {
                        buildText(builder,
                                "If you received any promotional message from this IP, without permission, make a complaint to "
                                        + Core.getAbuseEmail() + ".");
                    }
                }
            } else if (Block.containsHREF(ip)) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder, "Este IP est bloqueado para uso de URL.");
                    buildText(builder,
                            "Para que este IP seja removido desta lista,  necessrio enviar uma solicitao para "
                                    + Core.getAdminEmail() + ".");
                } else {
                    buildText(builder, "This IP is blocked for URL usage.");
                    buildText(builder, "In order to remove this IP from this list, you must send a request to "
                            + Core.getAdminEmail() + ".");
                }
            } else {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder, "Nenhum bloqueio foi encontrado para este IP.");
                    buildText(builder,
                            "Se este IP estiver sendo rejeitado por algum MTA, aguarde a propagao de DNS deste servio.");
                    buildText(builder, "O tempo de propagao pode levar alguns dias.");
                } else {
                    buildText(builder, "No block was found for this IP.");
                    buildText(builder,
                            "If this IP is being rejected by some MTA, wait for the DNS propagation of this service.");
                    buildText(builder, "The propagation time can take a few days.");
                }
            }
        }
    } else if (Domain.isHostname(query)) {
        Distribution distribution;
        String domain = Domain.normalizeHostname(query, true);
        if (domain.equals(".test") || domain.equals(".invalid")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este  um domnio reservado e por este motivo no  abordado nesta lista.");
            } else {
                buildText(builder,
                        "This is a reserved domain and for this reason is not addressed in this list.");
            }
        } else if (Generic.containsDynamic(domain)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este hostname est listado por referncia a um padro de <a target=\"_blank\" href=\"http://spfbl.net/dynamic/\">IP dinmico</a>.");
                if (Core.hasAdminEmail()) {
                    buildText(builder,
                            "Se voc discorda que se trata de hostname com padro de <a target=\"_blank\" href=\"http://spfbl.net/dynamic/\">IP dinmico</a>, entre em contato conosco atravs do e-mail "
                                    + Core.getAdminEmail() + ".");
                }
            } else {
                buildText(builder,
                        "This hostname is listed by reference to a <a target=\"_blank\" href=\"http://spfbl.net/en/dynamic/\">dynamic IP</a> pattern.");
                if (Core.hasAdminEmail()) {
                    buildText(builder,
                            "If you disagree that this is hostname with <a target=\"_blank\" href=\"http://spfbl.net/en/dynamic/\">dynamic IP</a> pattern, contact us by email "
                                    + Core.getAdminEmail() + ".");
                }
            }
        } else if ((distribution = SPF.getDistribution(domain, true)).isNotGreen(domain)) {
            float probability = distribution.getSpamProbability(domain);
            boolean blocked = Block.containsDomain(domain, false);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este domnio " + (blocked ? "foi bloqueado" : "est listado")
                                + " por m reputao com " + Core.PERCENT_FORMAT.format(probability)
                                + " de pontos negativos do volume total de envio.");
                buildText(builder,
                        "Para que este domnio possa ser removido desta lista,  necessrio que todos os MTAs de origem reduzam o volume de envios para os destinatrios com <a target=\"_blank\" href=\"http://spfbl.net/feedback/\">prefixo de rejeio SPFBL</a> na camada SMTP.");
            } else {
                buildText(builder, "This domain " + (blocked ? "was blocked" : "is listed")
                        + " by poor reputation in " + Core.PERCENT_FORMAT.format(probability)
                        + " of negative points of total sending the recipients with <a target=\"_blank\" href=\"http://spfbl.net/en/feedback/\">SPFBL rejection prefix</a> at SMTP layer.");
            }
        } else if (Block.containsDomain(domain, true)) {
            if (Reverse.isInexistentDomain(domain)) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder, "Este domnio est listado por no existir oficialmente.");
                } else {
                    buildText(builder, "This domain is listed because it does not exist officially.");
                }
            } else {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    buildText(builder, "Este domnio est listado por bloqueio manual.");
                    if (Core.hasAdminEmail()) {
                        buildText(builder,
                                "Para que este domnio seja removido desta lista,  necessrio enviar uma solicitao para "
                                        + Core.getAdminEmail() + ".");
                    }
                } else {
                    buildText(builder, "This domain is listed by manual block.");
                    if (Core.hasAdminEmail()) {
                        buildText(builder,
                                "In order to remove this domain from this list, you must send a request to "
                                        + Core.getAdminEmail() + ".");
                    }
                }
            }
        } else if (SPF.isGood(domain)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este domnio est com reputao extremamente boa e por isso foi colocado em lista branca.");
            } else {
                buildText(builder,
                        "This domain is extremely good reputation and therefore has been whitelisted.");
            }
        } else if (Ignore.containsHost(domain)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este domnio est marcado como servio essencial e por isso foi colocado em lista branca.");
            } else {
                buildText(builder,
                        "This domain is marked as an essential service and therefore has been whitelisted.");
            }
        } else if (White.containsDomain(domain)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este domnio est marcado como servio de mensagem estritamente corporativo e por isso foi colocado em lista branca.");
                if (Core.hasAbuseEmail()) {
                    buildText(builder,
                            "Se voc tiver recebido alguma mensagem promocional deste domnio, sem prvia autorizao, faa uma denuncia para "
                                    + Core.getAbuseEmail() + ".");
                }
            } else {
                buildText(builder,
                        "This domain is marked as strictly corporate message service and therefore has been whitelisted.");
                if (Core.hasAbuseEmail()) {
                    buildText(builder,
                            "If you received any promotional message from this domain, without permission, make a complaint to "
                                    + Core.getAbuseEmail() + ".");
                }
            }
        } else if (Block.containsHREF(domain)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder, "Este domnio est bloqueado para uso em URL.");
                if (Core.hasAdminEmail()) {
                    buildText(builder,
                            "Para que este domnio seja removido desta lista,  necessrio enviar uma solicitao para "
                                    + Core.getAdminEmail() + ".");
                }
            } else {
                buildText(builder, "This domain is blocked for URL usage.");
                if (Core.hasAdminEmail()) {
                    buildText(builder,
                            "In order to remove this domain from this list, you must send a request to "
                                    + Core.getAdminEmail() + ".");
                }
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder, "Nenhum bloqueio foi encontrado para este domnio.");
            } else {
                buildText(builder, "No block was found for this domain.");
            }
        }
    }
    buildFooter(builder, locale);
    builder.append("    </div>\n");
    builder.append("  </body>\n");
    builder.append("</html>\n");
    return builder.toString();
}

From source file:net.spfbl.http.ServerHTTP.java

private static void buildQueryRow(Locale locale, StringBuilder builder, DateFormat dateFormat,
        GregorianCalendar calendar, long time, User.Query query, boolean highlight) {
    if (query != null) {
        calendar.setTimeInMillis(time);// ww w  .  j  a  v a 2  s.c o  m
        String ip = query.getIP();
        String hostname = query.getValidHostname();
        String sender = query.getSender();
        String from = query.getFrom();
        String replyto = query.getReplyTo();
        String subject = query.getSubject();
        String malware = query.getMalware();
        String recipient = query.getRecipient();
        String result = query.getResult();
        builder.append("        <tr id=\"");
        builder.append(time);
        builder.append("\"");
        if (highlight) {
            builder.append(" class=\"highlight\"");
        } else {
            builder.append(" class=\"click\"");
        }
        builder.append(" onclick=\"view('");
        builder.append(time);
        builder.append("')\">\n");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("          <td style=\"width:120px;\">");
        } else {
            builder.append("          <td style=\"width:160px;\">");
        }
        builder.append(dateFormat.format(calendar.getTime()));
        builder.append("<br>");
        builder.append(query.getClient());
        builder.append("</td>\n");
        builder.append("          <td>");
        if (hostname == null) {
            String helo = query.getHELO();
            if (helo == null) {
                builder.append(ip);
            } else if (Subnet.isValidIP(helo)) {
                builder.append(ip);
            } else {
                builder.append(ip);
                builder.append("<br>");
                builder.append("<strike>");
                builder.append(helo);
                builder.append("</strike>");
            }
        } else if (Generic.containsDynamicDomain(hostname)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><i>Dinmico</i></small>");
            } else {
                builder.append("<small><i>Dynamic</i></small>");
            }
            builder.append("<br>");
            builder.append(hostname);
        } else if (Generic.containsGenericDomain(hostname)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><i>Genrico</i></small>");
            } else {
                builder.append("<small><i>Generic</i></small>");
            }
            builder.append("<br>");
            builder.append(hostname);
        } else if (Provider.containsDomain(hostname)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><i>Provedor</i></small>");
            } else {
                builder.append("<small><i>Provider</i></small>");
            }
            builder.append("<br>");
            builder.append(hostname);
        } else {
            builder.append(hostname);
        }
        builder.append("</td>\n");
        TreeSet<String> senderSet = new TreeSet<String>();
        builder.append("          <td>");
        if (sender == null) {
            builder.append("MAILER-DAEMON");
        } else {
            senderSet.add(sender);
            String qualifier = query.getQualifierName();
            if (qualifier.equals("PASS")) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Comprovadamente autntico</i></small>");
                } else {
                    builder.append("<small><i>Proved genuine</i></small>");
                }
            } else if (qualifier.equals("FAIL")) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Comprovadamente falso</i></small>");
                } else {
                    builder.append("<small><i>Proved false</i></small>");
                }
            } else if (qualifier.equals("SOFTFAIL")) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Pode ser falso</i></small>");
                } else {
                    builder.append("<small><i>May be false</i></small>");
                }
            } else {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Pode ser autntico</i></small>");
                } else {
                    builder.append("<small><i>May be genuine</i></small>");
                }
            }
            builder.append("<br>");
            builder.append(sender);
        }
        boolean lineSeparator = false;
        if (from != null && !senderSet.contains(from)) {
            senderSet.add(from);
            builder.append("<hr style=\"height:0px;visibility:hidden;margin-bottom:0px;\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><b>De:</b> ");
            } else {
                builder.append("<small><b>From:</b> ");
            }
            builder.append(from);
            builder.append("</small>");
            lineSeparator = true;
        }
        if (replyto != null && !senderSet.contains(replyto)) {
            senderSet.add(replyto);
            if (lineSeparator) {
                builder.append("<br>");
            } else {
                builder.append("<hr style=\"height:0px;visibility:hidden;margin-bottom:0px;\">");
            }
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><b>Responder para:</b> ");
            } else {
                builder.append("<small><b>Reply to:</b> ");
            }
            builder.append(replyto);
            builder.append("</small>");
        }
        builder.append("</td>\n");
        builder.append("          <td>");
        if (subject != null) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><b>Assunto:</b> ");
            } else {
                builder.append("<small><b>Subject:</b> ");
            }
            builder.append(subject);
            builder.append("</small>");
            builder.append("<hr style=\"height:0px;visibility:hidden;margin-bottom:0px;\">");
        }
        if (malware == null) {
            TreeSet<String> linkSet = query.getLinkSet();
            if (linkSet == null) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Corpo no verificado</i></small>");
                } else {
                    builder.append("<small><i>Body not verified</i></small>");
                }
            } else if (linkSet.isEmpty()) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Sem links</i></small>");
                } else {
                    builder.append("<small><i>No links</i></small>");
                }
            } else {
                String link = linkSet.pollFirst();
                if (query.isLinkBlocked(link)) {
                    builder.append("<font color=\"DarkRed\"><b>");
                    builder.append(link);
                    builder.append("</b></font>");
                } else {
                    builder.append(link);
                }
                while (!linkSet.isEmpty()) {
                    builder.append("<br>");
                    link = linkSet.pollFirst();
                    if (query.isLinkBlocked(link)) {
                        builder.append("<font color=\"DarkRed\"><b>");
                        builder.append(link);
                        builder.append("</b></font>");
                    } else {
                        builder.append(link);
                    }
                }
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><i>Malware encontrado</i></small>");
            } else {
                builder.append("<small><i>Malware found</i></small>");
            }
            if (!malware.equals("FOUND")) {
                builder.append("<br>");
                builder.append("<font color=\"DarkRed\"><b>");
                builder.append(malware);
                builder.append("</b></font>");
            }
        }
        builder.append("</td>\n");
        builder.append("          <td>");
        if (result.equals("REJECT")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada pelo contedo");
            } else {
                builder.append("Rejected by content");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("BLOCK") || result.equals("BLOCKED")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por bloqueio");
            } else {
                builder.append("Rejected by blocking");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("FAIL") || result.equals("FAILED")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por falsidade");
            } else {
                builder.append("Rejected by falseness");
            }
        } else if (result.equals("INVALID")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por origem invlida");
            } else {
                builder.append("Rejected by invalid source");
            }
        } else if (result.equals("GREYLIST")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Atrasada por greylisting");
            } else {
                builder.append("Delayed by greylisting");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("SPAMTRAP") || result.equals("TRAP")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Descartado pela armadilha");
            } else {
                builder.append("Discarded by spamtrap");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("INEXISTENT")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por inexistncia");
            } else {
                builder.append("Rejected by non-existence");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("WHITE")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria");
            } else {
                builder.append("Priority delivery");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("ACCEPT")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega aceita");
            } else {
                builder.append("Accepted for delivery");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("FLAG")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Marcada como suspeita");
            } else {
                builder.append("Marked as suspect");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("HOLD")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega retida");
            } else {
                builder.append("Delivery retained");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("NXDOMAIN")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por domnio inexistente");
            } else {
                builder.append("Rejected by non-existent domain");
            }
        } else if (result.equals("NXSENDER")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por remetente inexistente");
            } else {
                builder.append("Rejected by non-existent sender");
            }
        } else {
            builder.append(result);
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        }
        builder.append("</td>\n");
        builder.append("        </tr>\n");
    }
}

From source file:net.spfbl.spf.SPF.java

/**
 * Processa a consulta e retorna o resultado.
 *
 * @param query a expresso da consulta./*from  w ww. java 2s.com*/
 * @return o resultado do processamento.
 */
protected static String processSPF(InetAddress ipAddress, Client client, User user, String query,
        LinkedList<User> userList) {
    try {
        String result = "";
        if (query.length() == 0) {
            return "INVALID QUERY\n";
        } else {
            String origin;
            if (client == null) {
                origin = ipAddress.getHostAddress();
            } else if (client.hasEmail()) {
                origin = ipAddress.getHostAddress() + " " + client.getDomain() + " " + client.getEmail();
            } else {
                origin = ipAddress.getHostAddress() + " " + client.getDomain();
            }
            StringTokenizer tokenizer = new StringTokenizer(query, " ");
            String firstToken = tokenizer.nextToken();
            if (firstToken.equals("SPAM") && tokenizer.countTokens() == 1) {
                String ticket = tokenizer.nextToken();
                TreeSet<String> tokenSet = addComplainURLSafe(origin, ticket, null);
                if (tokenSet == null) {
                    result = "DUPLICATE COMPLAIN\n";
                } else {
                    String userEmail;
                    try {
                        userEmail = SPF.getClientURLSafe(ticket);
                    } catch (Exception ex) {
                        userEmail = client == null ? null : client.getEmail();
                    }
                    user = User.get(userEmail);
                    if (user != null) {
                        userList.add(user);
                    }
                    String recipient;
                    try {
                        recipient = SPF.getRecipientURLSafe(ticket);
                    } catch (ProcessException ex) {
                        recipient = null;
                    }
                    result = "OK " + tokenSet + (recipient == null ? "" : " >" + recipient) + "\n";
                }
            } else if (firstToken.equals("ABUSE") && tokenizer.hasMoreTokens()) {
                String token = tokenizer.nextToken();
                if (token.startsWith("In-Reply-To:") && tokenizer.countTokens() == 1) {
                    token = tokenizer.nextToken();
                    if (token.startsWith("From:")) {
                        int index = token.indexOf(':') + 1;
                        String recipient = token.substring(index);
                        User recipientUser = User.get(recipient);
                        if (recipientUser == null) {
                            // Se a consulta originar de destinatrio com postmaster cadastrado,
                            // considerar o prprio postmaster como usurio da consulta.
                            index = recipient.indexOf('@');
                            String postmaster = "postmaster" + recipient.substring(index);
                            User postmasterUser = User.get(postmaster);
                            if (postmasterUser != null) {
                                userList.add(user = postmasterUser);
                            }
                        } else {
                            userList.add(user = recipientUser);
                        }
                        index = query.indexOf(':') + 1;
                        String messageID = query.substring(index);
                        result = "INVALID ID\n";
                        index = messageID.indexOf('<');
                        if (index >= 0) {
                            messageID = messageID.substring(index + 1);
                            index = messageID.indexOf('>');
                            if (index > 0) {
                                messageID = messageID.substring(0, index);
                                result = user.blockByMessageID(messageID) + '\n';
                            }
                        }
                    } else {
                        result = "INVALID FROM\n";
                    }
                } else {
                    result = "INVALID COMMAND\n";
                }
            } else if (firstToken.equals("HOLDING") && tokenizer.countTokens() == 1) {
                String ticket = tokenizer.nextToken();
                result = getHoldStatus(client, ticket, userList) + '\n';
            } else if (firstToken.equals("LINK") && tokenizer.hasMoreTokens()) {
                String ticketSet = tokenizer.nextToken();
                TreeSet<String> linkSet = new TreeSet<String>();
                while (tokenizer.hasMoreTokens()) {
                    linkSet.add(tokenizer.nextToken());
                }
                StringTokenizer tokenizerTicket = new StringTokenizer(ticketSet, ";");
                String unblockURL = null;
                boolean blocked = false;
                Action action = null;
                while (tokenizerTicket.hasMoreTokens()) {
                    String ticket = tokenizerTicket.nextToken();
                    String userEmail;
                    try {
                        userEmail = SPF.getClientURLSafe(ticket);
                    } catch (Exception ex) {
                        userEmail = client == null ? null : client.getEmail();
                    }
                    if ((user = User.get(userEmail)) != null) {
                        userList.add(user);
                        long dateTicket = SPF.getDateTicket(ticket);
                        User.Query queryTicket = user.getQuery(dateTicket);
                        if (queryTicket != null) {
                            if (queryTicket.setLinkSet(linkSet)) {
                                SPF.setSpam(dateTicket, queryTicket.getTokenSet());
                                if (!queryTicket.isWhite() && queryTicket.blockSender(dateTicket)) {
                                    Server.logDebug(
                                            "new BLOCK '" + queryTicket.getBlockSender() + "' added by LINK.");
                                }
                                action = client == null ? Action.REJECT : client.getActionBLOCK();
                                unblockURL = queryTicket.getUnblockURL();
                                blocked = true;
                            } else if (queryTicket.isAnyLinkRED()) {
                                action = client == null ? Action.FLAG : client.getActionRED();
                            }
                            if (action == Action.HOLD) {
                                queryTicket.setResult("HOLD");
                            } else if (action == Action.FLAG) {
                                queryTicket.setResult("FLAG");
                            } else if (action == Action.REJECT) {
                                queryTicket.setResult("REJECT");
                            }
                            User.storeDB(dateTicket, queryTicket);
                        }
                    }
                }
                if (unblockURL != null) {
                    result = "BLOCKED " + unblockURL + "\n";
                } else if (blocked) {
                    result = "BLOCKED\n";
                } else if (action == Action.HOLD) {
                    result = "HOLD\n";
                } else if (action == Action.FLAG) {
                    result = "FLAG\n";
                } else if (action == Action.REJECT) {
                    result = "REJECT\n";
                } else {
                    result = "CLEAR\n";
                }
            } else if (firstToken.equals("MALWARE") && tokenizer.hasMoreTokens()) {
                String ticketSet = tokenizer.nextToken();
                StringBuilder nameBuilder = new StringBuilder();
                while (tokenizer.hasMoreTokens()) {
                    if (nameBuilder.length() > 0) {
                        nameBuilder.append(' ');
                    }
                    nameBuilder.append(tokenizer.nextToken());
                }
                StringBuilder resultBuilder = new StringBuilder();
                StringTokenizer ticketTokenizer = new StringTokenizer(ticketSet, ";");
                while (ticketTokenizer.hasMoreTokens()) {
                    String ticket = ticketTokenizer.nextToken();
                    TreeSet<String> tokenSet = addComplainURLSafe(origin, ticket, "MALWARE");
                    if (tokenSet == null) {
                        resultBuilder.append("DUPLICATE COMPLAIN\n");
                    } else {
                        // Processar reclamao.
                        String userEmail;
                        try {
                            userEmail = SPF.getClientURLSafe(ticket);
                        } catch (Exception ex) {
                            userEmail = client == null ? null : client.getEmail();
                        }
                        user = User.get(userEmail);
                        if (user != null) {
                            userList.add(user);
                            long dateTicket = getDateTicket(ticket);
                            User.Query userQuery = user.getQuery(dateTicket);
                            if (userQuery != null && userQuery.setMalware(nameBuilder.toString())) {
                                User.storeDB(dateTicket, userQuery);
                            }
                        }
                        String recipient;
                        try {
                            recipient = SPF.getRecipientURLSafe(ticket);
                        } catch (ProcessException ex) {
                            recipient = null;
                        }
                        // Bloquear automaticamente todos
                        // os tokens com reputao amarela ou vermelha.
                        // Processar reclamao.
                        for (String token : tokenSet) {
                            String block;
                            Status status = SPF.getStatus(token);
                            if (status == Status.RED && (block = Block.add(token)) != null) {
                                Server.logDebug(
                                        "new BLOCK '" + block + "' added by '" + recipient + ";MALWARE'.");
                                Peer.sendBlockToAll(block);
                            }
                            if (status != Status.GREEN && !Subnet.isValidIP(token)
                                    && (block = Block.addIfNotNull(user, token)) != null) {
                                Server.logDebug(
                                        "new BLOCK '" + block + "' added by '" + recipient + ";MALWARE'.");
                            }
                        }
                        resultBuilder.append("OK ");
                        resultBuilder.append(tokenSet);
                        resultBuilder.append(recipient == null ? "" : " >" + recipient);
                        resultBuilder.append("\n");
                    }
                }
                result = resultBuilder.toString();
            } else if (firstToken.equals("HEADER") && tokenizer.hasMoreTokens()) {
                String ticketSet = tokenizer.nextToken();
                String key = null;
                String from = null;
                String replyto = null;
                String messageID = null;
                String unsubscribe = null;
                String subject = null;
                while (tokenizer.hasMoreTokens()) {
                    String token = tokenizer.nextToken();
                    if (token.startsWith("From:")) {
                        key = "From";
                        int index = token.indexOf(':');
                        from = token.substring(index + 1);
                    } else if (token.startsWith("ReplyTo:") || token.startsWith("Reply-To:")) {
                        key = "Reply-To";
                        int index = token.indexOf(':');
                        replyto = token.substring(index + 1);
                    } else if (token.startsWith("Message-ID:")) {
                        key = "Message-ID";
                        int index = token.indexOf(':');
                        messageID = token.substring(index + 1);
                    } else if (token.startsWith("List-Unsubscribe:")) {
                        key = "List-Unsubscribe";
                        int index = token.indexOf(':');
                        unsubscribe = token.substring(index + 1);
                    } else if (token.startsWith("Subject:")) {
                        key = "Subject";
                        int index = token.indexOf(':');
                        subject = token.substring(index + 1);
                    } else if (key == null) {
                        from = null;
                        replyto = null;
                        unsubscribe = null;
                        subject = null;
                        break;
                    } else if (key.equals("From")) {
                        from += ' ' + token;
                    } else if (key.equals("Reply-To")) {
                        replyto += ' ' + token;
                    } else if (key.equals("Message-ID")) {
                        messageID += ' ' + token;
                    } else if (key.equals("List-Unsubscribe")) {
                        unsubscribe += ' ' + token;
                    } else if (key.equals("Subject")) {
                        subject += ' ' + token;
                    }
                }
                if ((from == null || from.length() == 0) && (replyto == null || replyto.length() == 0)
                        && (messageID == null || messageID.length() == 0)
                        && (unsubscribe == null || unsubscribe.length() == 0)
                        && (subject == null || subject.length() == 0)) {
                    result = "INVALID COMMAND\n";
                } else {
                    boolean whitelisted = false;
                    boolean blocklisted = false;
                    TreeSet<String> unblockURLSet = new TreeSet<String>();
                    StringTokenizer ticketRokenizer = new StringTokenizer(ticketSet, ";");
                    int n = ticketRokenizer.countTokens();
                    ArrayList<User.Query> queryList = new ArrayList<User.Query>(n);
                    while (ticketRokenizer.hasMoreTokens()) {
                        String ticket = ticketRokenizer.nextToken();
                        String userEmail;
                        try {
                            userEmail = SPF.getClientURLSafe(ticket);
                        } catch (Exception ex) {
                            userEmail = client == null ? null : client.getEmail();
                        }
                        if ((user = User.get(userEmail)) != null) {
                            userList.add(user);
                            long dateTicket = SPF.getDateTicket(ticket);
                            User.Query queryTicket = user.getQuery(dateTicket);
                            if (queryTicket != null) {
                                queryList.add(queryTicket);
                                String resultLocal = queryTicket.setHeader(from, replyto, subject, messageID,
                                        unsubscribe);
                                if ("WHITE".equals(resultLocal)) {
                                    whitelisted = true;
                                } else if ("BLOCK".equals(resultLocal)) {
                                    blocklisted = true;
                                    String url = queryTicket.getUnblockURL();
                                    if (url != null) {
                                        unblockURLSet.add(url);
                                    }
                                }
                                User.storeDB(dateTicket, queryTicket);
                            }
                        }
                    }
                    if (whitelisted) {
                        for (User.Query queryTicket : queryList) {
                            queryTicket.setResult("WHITE");
                        }
                        result = "WHITE\n";
                    } else if (blocklisted) {
                        for (User.Query queryTicket : queryList) {
                            queryTicket.setResult("BLOCK");
                        }
                        if (unblockURLSet.size() == 1) {
                            result = "BLOCKED " + unblockURLSet.first() + "\n";
                        } else {
                            result = "BLOCKED\n";
                        }
                    } else {
                        result = "CLEAR\n";
                    }
                }
            } else if (firstToken.equals("HAM") && tokenizer.countTokens() == 1) {
                String ticket = tokenizer.nextToken();
                TreeSet<String> tokenSet = deleteComplainURLSafe(origin, ticket);
                if (tokenSet == null) {
                    result = "ALREADY REMOVED\n";
                } else {
                    String recipient;
                    try {
                        recipient = SPF.getRecipientURLSafe(ticket);
                    } catch (ProcessException ex) {
                        recipient = null;
                    }
                    result = "OK " + tokenSet + (recipient == null ? "" : " >" + recipient) + "\n";
                }
            } else if (firstToken.equals("REFRESH") && tokenizer.countTokens() == 1) {
                String address = tokenizer.nextToken();
                try {
                    if (CacheSPF.refresh(address, true)) {
                        result = "UPDATED\n";
                    } else {
                        result = "NOT LOADED\n";
                    }
                } catch (ProcessException ex) {
                    result = ex.getMessage() + "\n";
                }
            } else if ((firstToken.equals("SPF") && tokenizer.countTokens() >= 4)
                    || tokenizer.countTokens() == 2 || tokenizer.countTokens() == 1
                    || (firstToken.equals("CHECK") && tokenizer.countTokens() == 4)
                    || (firstToken.equals("CHECK") && tokenizer.countTokens() == 3)
                    || (firstToken.equals("CHECK") && tokenizer.countTokens() == 2)) {
                try {
                    String ip;
                    String sender;
                    String helo;
                    String recipient;
                    String origem;
                    String fluxo;
                    if (firstToken.equals("SPF")) {
                        // Nova formatao de consulta.
                        ip = tokenizer.nextToken();
                        sender = tokenizer.nextToken();
                        while (!sender.endsWith("'") && tokenizer.hasMoreTokens()) {
                            sender += " " + tokenizer.nextToken();
                        }
                        helo = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : "''";
                        recipient = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : "''";
                        ip = ip.substring(1, ip.length() - 1);
                        sender = sender.substring(1, sender.length() - 1);
                        helo = helo.substring(1, helo.length() - 1);
                        if (recipient.equals("'")) {
                            recipient = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : "";
                            if (recipient.endsWith("'")) {
                                recipient = recipient.substring(0, recipient.length() - 1);
                            }
                        } else {
                            recipient = recipient.substring(1, recipient.length() - 1);
                        }
                        if (sender.length() == 0) {
                            sender = null;
                        } else {
                            sender = sender.toLowerCase();
                        }
                        recipient = recipient.toLowerCase();
                        recipient = recipient.replace("\"", "");
                    } else if (firstToken.equals("CHECK") && tokenizer.countTokens() == 4) {
                        ip = tokenizer.nextToken().toLowerCase();
                        sender = tokenizer.nextToken().toLowerCase();
                        helo = tokenizer.nextToken();
                        recipient = tokenizer.nextToken().toLowerCase();
                        if (ip.startsWith("'") && ip.endsWith("'")) {
                            ip = ip.substring(1, ip.length() - 1);
                        }
                        if (sender.startsWith("'") && sender.endsWith("'")) {
                            sender = sender.substring(1, sender.length() - 1);
                        }
                        if (helo.startsWith("'") && helo.endsWith("'")) {
                            helo = helo.substring(1, helo.length() - 1);
                        }
                        if (recipient.startsWith("'") && recipient.endsWith("'")) {
                            recipient = recipient.substring(1, recipient.length() - 1);
                        }
                        if (ip.length() == 0) {
                            ip = null;
                        }
                        if (sender.length() == 0) {
                            sender = null;
                        }
                        if (!Domain.isHostname(helo)) {
                            helo = null;
                        }
                        if (recipient.length() == 0) {
                            recipient = null;
                        } else {
                            recipient = recipient.toLowerCase();
                        }
                    } else {
                        // Manter compatibilidade da verso antiga.
                        // Verso obsoleta.
                        if (firstToken.equals("CHECK")) {
                            ip = tokenizer.nextToken();
                        } else {
                            ip = firstToken;
                        }
                        if (tokenizer.countTokens() == 2) {
                            sender = tokenizer.nextToken().toLowerCase();
                            helo = tokenizer.nextToken();
                        } else {
                            sender = null;
                            helo = tokenizer.nextToken();
                        }
                        recipient = null;
                        if (ip.startsWith("'") && ip.endsWith("'")) {
                            ip = ip.substring(1, ip.length() - 1);
                        }
                        if (sender != null && sender.startsWith("'") && sender.endsWith("'")) {
                            sender = sender.substring(1, sender.length() - 1);
                            if (sender.length() == 0) {
                                sender = null;
                            }
                        }
                        if (helo.startsWith("'") && helo.endsWith("'")) {
                            helo = helo.substring(1, helo.length() - 1);
                        }
                    }
                    if (!Subnet.isValidIP(ip)) {
                        return "INVALID\n";
                    } else if (sender != null && !Domain.isEmail(sender)) {
                        return "INVALID\n";
                    } else if (recipient != null && !Domain.isEmail(recipient)) {
                        return "INVALID\n";
                    } else if (Subnet.isReservedIP(ip)) {
                        // Message from LAN.
                        return "LAN\n";
                    } else if (client != null && client.containsFull(ip)) {
                        // Message from LAN.
                        return "LAN\n";
                    } else {
                        TreeSet<String> tokenSet = new TreeSet<String>();
                        ip = Subnet.normalizeIP(ip);
                        tokenSet.add(ip);
                        if (Domain.isValidEmail(recipient)) {
                            // Se houver um remetente vlido,
                            // Adicionar no ticket para controle.
                            tokenSet.add('>' + recipient);
                        }
                        if (recipient != null) {
                            User recipientUser = User.get(recipient);
                            if (recipientUser == null) {
                                // Se a consulta originar de destinatrio com postmaster cadastrado,
                                // considerar o prprio postmaster como usurio da consulta.
                                int index = recipient.indexOf('@');
                                String postmaster = "postmaster" + recipient.substring(index);
                                User postmasterUser = User.get(postmaster);
                                if (postmasterUser != null) {
                                    user = postmasterUser;
                                }
                            } else {
                                user = recipientUser;
                            }
                        }
                        if (user != null) {
                            userList.add(user);
                            tokenSet.add(user.getEmail() + ':');
                        } else if (client != null && client.hasEmail()) {
                            tokenSet.add(client.getEmail() + ':');
                        }
                        // Passar a acompanhar todos os 
                        // HELO quando apontados para o IP para 
                        // uma nova forma de interpretar dados.
                        String hostname;
                        if (CacheHELO.match(ip, helo, false)) {
                            hostname = Domain.normalizeHostname(helo, true);
                        } else {
                            hostname = Reverse.getHostname(ip);
                            hostname = Domain.normalizeHostname(hostname, true);
                        }
                        if (hostname == null) {
                            Server.logDebug("no rDNS for " + ip + ".");
                        } else if (Domain.isOfficialTLD(hostname)) {
                            return "INVALID\n";
                        } else {
                            // Verificao de pilha dupla,
                            // para pontuao em ambas pilhas.
                            String ipv4 = CacheHELO.getUniqueIPv4(hostname);
                            String ipv6 = CacheHELO.getUniqueIPv6(hostname);
                            if (ip.equals(ipv6) && CacheHELO.match(ipv4, hostname, false)) {
                                // Equivalncia de pilha dupla se 
                                // IPv4 for nico para o hostname.
                                tokenSet.add(ipv4);
                            } else if (ip.equals(ipv4) && CacheHELO.match(ipv6, hostname, false)) {
                                // Equivalncia de pilha dupla se 
                                // IPv6 for nico para o hostname.
                                tokenSet.add(ipv6);
                            }
                        }
                        if (Generic.containsGenericSoft(hostname)) {
                            // Quando o reverso for 
                            // genrico, no consider-lo.
                            hostname = null;
                        } else if (hostname != null) {
                            tokenSet.add(hostname);
                        }
                        LinkedList<String> logList = null;
                        if (sender != null && firstToken.equals("CHECK")) {
                            int index = sender.lastIndexOf('@');
                            String domain = sender.substring(index + 1);
                            logList = new LinkedList<String>();
                            try {
                                CacheSPF.refresh(domain, false);
                            } catch (ProcessException ex) {
                                logList.add("Cannot refresh SPF registry: " + ex.getErrorMessage());
                                logList.add("Using cached SPF registry.");
                            }
                        }
                        SPF spf;
                        if (sender == null) {
                            spf = null;
                            result = "NONE";
                        } else if (Domain.isOfficialTLD(sender)) {
                            spf = null;
                            result = "NONE";
                        } else if (Generic.containsGeneric(sender)) {
                            spf = null;
                            result = "NONE";
                        } else if ((spf = CacheSPF.get(sender)) == null) {
                            result = "NONE";
                        } else if (spf.isInexistent()) {
                            result = "NONE";
                        } else {
                            result = spf.getResult(ip, sender, helo, logList);
                        }
                        String mx = Domain.extractHost(sender, true);
                        if (user != null && user.isLocal()) {
                            // Message from local user.
                            return "LAN\n";
                        } else if (recipient != null && result.equals("PASS")) {
                            if (recipient.endsWith(mx)) {
                                // Message from same domain.
                                return "LAN\n";
                            } else if (recipient.equals(Core.getAbuseEmail())
                                    && User.exists(sender, "postmaster" + mx)) {
                                // Message to abuse.
                                return "LAN\n";
                            }
                        }
                        if (result.equals("PASS") || (sender != null && Provider.containsHELO(ip, hostname))) {
                            // Quando fo PASS, significa que o domnio
                            // autorizou envio pelo IP, portanto o dono dele
                            //  responsavel pelas mensagens.
                            if (!Provider.containsExact(mx)) {
                                // No  um provedor ento
                                // o MX deve ser listado.
                                tokenSet.add(mx);
                                origem = mx;
                            } else if (Domain.isValidEmail(sender)) {
                                // Listar apenas o remetente se o
                                // hostname for um provedor de e-mail.
                                String userEmail = null;
                                String recipientEmail = null;
                                for (String token : tokenSet) {
                                    if (token.endsWith(":")) {
                                        userEmail = token;
                                    } else if (token.startsWith(">")) {
                                        recipientEmail = token;
                                    }
                                }
                                tokenSet.clear();
                                tokenSet.add(sender);
                                if (userEmail != null) {
                                    tokenSet.add(userEmail);
                                }
                                if (recipientEmail != null) {
                                    tokenSet.add(recipientEmail);
                                }
                                origem = sender;
                            } else {
                                origem = sender;
                            }
                            fluxo = origem + ">" + recipient;
                        } else if (hostname == null) {
                            origem = (sender == null ? "" : sender + '>') + ip;
                            fluxo = origem + ">" + recipient;
                        } else {
                            String dominio = Domain.extractDomain(hostname, true);
                            origem = (sender == null ? "" : sender + '>')
                                    + (dominio == null ? hostname : dominio.substring(1));
                            fluxo = origem + ">" + recipient;
                        }
                        Long recipientTrapTime = Trap.getTimeRecipient(client, user, recipient);
                        if (firstToken.equals("CHECK")) {
                            String results = "\nSPF resolution results:\n";
                            if (spf != null && spf.isInexistent()) {
                                results += "   NXDOMAIN\n";
                            } else if (logList == null || logList.isEmpty()) {
                                results += "   NONE\n";
                            } else {
                                for (String log : logList) {
                                    results += "   " + log + "\n";
                                }
                            }
                            String white;
                            String block;
                            if ((white = White.find(client, user, ip, sender, hostname, result,
                                    recipient)) != null) {
                                results += "\nFirst WHITE match: " + white + "\n";
                            } else if ((block = Block.find(client, user, ip, sender, hostname, result,
                                    recipient, false, true, true, false)) != null) {
                                results += "\nFirst BLOCK match: " + block + "\n";
                            }
                            TreeSet<String> graceSet = new TreeSet<String>();
                            if (Domain.isGraceTime(sender)) {
                                graceSet.add(Domain.extractDomain(sender, false));
                            }
                            if (Domain.isGraceTime(hostname)) {
                                graceSet.add(Domain.extractDomain(hostname, false));
                            }
                            if (!graceSet.isEmpty()) {
                                results += "\n";
                                results += "Domains in grace time:\n";
                                for (String grace : graceSet) {
                                    results += "   " + grace + "\n";
                                }
                            }
                            results += "\n";
                            results += "Considered identifiers and status:\n";
                            tokenSet = expandTokenSet(tokenSet);
                            TreeMap<String, Distribution> distributionMap = CacheDistribution.getMap(tokenSet);
                            int count = 0;
                            for (String token : tokenSet) {
                                if (!token.startsWith(">") && !token.endsWith(":")) {
                                    if (!Ignore.contains(token)) {
                                        float probability;
                                        Status status;
                                        if (distributionMap.containsKey(token)) {
                                            Distribution distribution = distributionMap.get(token);
                                            probability = distribution.getSpamProbability(token);
                                            status = distribution.getStatus(token);
                                        } else {
                                            probability = 0.0f;
                                            status = SPF.Status.GREEN;
                                        }
                                        results += "   " + token + " " + status.name() + " "
                                                + Core.DECIMAL_FORMAT.format(probability) + "\n";
                                        count++;
                                    }
                                }
                            }
                            if (count == 0) {
                                results += "   NONE\n";
                            }
                            results += "\n";
                            return results;
                        } else if (recipientTrapTime == null
                                && White.contains(client, user, ip, sender, hostname, result, recipient)) {
                            if (White.contains(client, user, ip, sender, hostname, result, null)) {
                                // Limpa da lista BLOCK um possvel falso positivo.
                                Block.clear(client, user, ip, sender, hostname, result, null);
                            }
                            // Calcula frequencia de consultas.
                            String url = Core.getURL();
                            String ticket = SPF.addQueryHam(client, user, ip, helo, hostname, sender, result,
                                    recipient, tokenSet, "WHITE");
                            return "WHITE " + (url == null ? ticket : url + ticket) + "\n";
                        } else if (Block.contains(client, user, ip, sender, hostname, result, recipient, true,
                                true, true, true)) {
                            Action action = client == null ? Action.REJECT : client.getActionBLOCK();
                            if (action == Action.REJECT) {
                                // Calcula frequencia de consultas.
                                long time = Server.getNewUniqueTime();
                                User.Query queryLocal = SPF.addQuerySpam(time, client, user, ip, helo, hostname,
                                        sender, result, recipient, tokenSet, "BLOCK");
                                action = client == null ? Action.FLAG : client.getActionRED();
                                if (action != Action.REJECT && queryLocal != null && queryLocal.needHeader()) {
                                    if (action == Action.FLAG) {
                                        queryLocal.setResult("FLAG");
                                        String url = Core.getURL();
                                        String ticket = SPF.createTicket(time, tokenSet);
                                        return "FLAG " + (url == null ? ticket : url + ticket) + "\n";
                                    } else if (action == Action.HOLD) {
                                        queryLocal.setResult("HOLD");
                                        String url = Core.getURL();
                                        String ticket = SPF.createTicket(time, tokenSet);
                                        return "HOLD " + (url == null ? ticket : url + ticket) + "\n";
                                    } else {
                                        return "ERROR: UNDEFINED ACTION\n";
                                    }
                                } else {
                                    String url = Core.getUnblockURL(client, user, ip, sender, hostname,
                                            recipient);
                                    if (url == null) {
                                        return "BLOCKED\n";
                                    } else {
                                        return "BLOCKED " + url + "\n";
                                    }
                                }
                            } else if (action == Action.FLAG) {
                                String url = Core.getURL();
                                String ticket = SPF.getTicket(client, user, ip, helo, hostname, sender, result,
                                        recipient, tokenSet, "FLAG");
                                return "FLAG " + (url == null ? ticket : url + ticket) + "\n";
                            } else if (action == Action.HOLD) {
                                String url = Core.getURL();
                                String ticket = SPF.getTicket(client, user, ip, helo, hostname, sender, result,
                                        recipient, tokenSet, "HOLD");
                                return "HOLD " + (url == null ? ticket : url + ticket) + "\n";
                            } else {
                                return "ERROR: UNDEFINED ACTION\n";
                            }
                        } else if (Generic.containsDynamicDomain(hostname)) {
                            // Bloquear automaticamente range de IP dinmico.
                            String cidr = Subnet
                                    .normalizeCIDR(SubnetIPv4.isValidIPv4(ip) ? ip + "/24" : ip + "/48");
                            if (Block.tryOverlap(cidr)) {
                                Server.logDebug(
                                        "new BLOCK '" + cidr + "' added by '" + hostname + ";DYNAMIC'.");
                            } else if (Block.tryAdd(ip)) {
                                Server.logDebug("new BLOCK '" + ip + "' added by '" + hostname + ";DYNAMIC'.");
                            }
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "INVALID");
                            return "INVALID\n";
                        } else if (spf != null && spf.isDefinitelyInexistent()) {
                            // Bloquear automaticamente IP com reputao vermelha.
                            if (SPF.isRed(ip)) {
                                if (Block.tryAdd(ip)) {
                                    Server.logDebug("new BLOCK '" + ip + "' added by '" + mx + ";NXDOMAIN'.");
                                }
                            }
                            Analise.processToday(ip);
                            // O domnio foi dado como inexistente inmeras vezes.
                            // Rejeitar e denunciar o host pois h abuso de tentativas.
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "NXDOMAIN");
                            return "NXDOMAIN\n";
                        } else if (spf != null && spf.isInexistent()) {
                            Analise.processToday(ip);
                            SPF.addQuery(client, user, ip, helo, hostname, sender, result, recipient, tokenSet,
                                    "NXDOMAIN");
                            return "NXDOMAIN\n";
                        } else if (result.equals("FAIL")) {
                            // Bloquear automaticamente IP com reputao vermelha.
                            if (SPF.isRed(ip)) {
                                if (Block.tryAdd(ip)) {
                                    Server.logDebug("new BLOCK '" + ip + "' added by '" + sender + ";FAIL'.");
                                }
                            }
                            Analise.processToday(ip);
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "FAIL");
                            // Retornar FAIL somente se no houver 
                            // liberao literal do remetente com FAIL.
                            return "FAIL\n";
                        } else if (sender != null && !Domain.isEmail(sender)) {
                            // Bloquear automaticamente IP com reputao vermelha.
                            if (SPF.isRed(ip)) {
                                if (Block.tryAdd(ip)) {
                                    Server.logDebug(
                                            "new BLOCK '" + ip + "' added by '" + sender + ";INVALID'.");
                                }
                            }
                            Analise.processToday(ip);
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "INVALID");
                            return "INVALID\n";
                        } else if (sender != null && Domain.isOfficialTLD(sender)) {
                            // Bloquear automaticamente IP com reputao vermelha.
                            if (SPF.isRed(ip)) {
                                if (Block.tryAdd(ip)) {
                                    Server.logDebug(
                                            "new BLOCK '" + ip + "' added by '" + sender + ";RESERVED'.");
                                }
                            }
                            Analise.processToday(ip);
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "INVALID");
                            return "INVALID\n";
                        } else if (sender == null && !CacheHELO.match(ip, hostname, false)) {
                            // Bloquear automaticamente IP com reputao ruim.
                            if (SPF.isRed(ip)) {
                                if (Block.tryAdd(ip)) {
                                    Server.logDebug("new BLOCK '" + ip + "' added by 'INVALID'.");
                                }
                            }
                            Analise.processToday(ip);
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "INVALID");
                            // HELO invlido sem remetente.
                            return "INVALID\n";
                        } else if (hostname == null && Core.isReverseRequired()) {
                            if (Block.tryAdd(ip)) {
                                Server.logDebug("new BLOCK '" + ip + "' added by 'NONE'.");
                            }
                            Analise.processToday(ip);
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "INVALID");
                            // Require a valid HELO or reverse.
                            return "INVALID\n";
                        } else if (recipient != null && !Domain.isValidEmail(recipient)) {
                            Analise.processToday(ip);
                            Analise.processToday(mx);
                            SPF.getTicket(client, user, ip, helo, hostname, sender, result, recipient, tokenSet,
                                    "INEXISTENT");
                            return "INEXISTENT\n";
                        } else if (recipientTrapTime != null) {
                            if (System.currentTimeMillis() > recipientTrapTime) {
                                // Spamtrap
                                for (String token : tokenSet) {
                                    String block;
                                    Status status = SPF.getStatus(token);
                                    if (status == Status.RED && (block = Block.add(token)) != null) {
                                        Server.logDebug("new BLOCK '" + block + "' added by '" + recipient
                                                + ";SPAMTRAP'.");
                                        Peer.sendBlockToAll(block);
                                    }
                                    if (status != Status.GREEN && !Subnet.isValidIP(token)
                                            && (block = Block.addIfNotNull(user, token)) != null) {
                                        Server.logDebug("new BLOCK '" + block + "' added by '" + recipient
                                                + ";SPAMTRAP'.");
                                    }
                                }
                                Analise.processToday(ip);
                                Analise.processToday(mx);
                                // Calcula frequencia de consultas.
                                SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                        tokenSet, "TRAP");
                                return "SPAMTRAP\n";
                            } else {
                                // Inexistent
                                for (String token : tokenSet) {
                                    String block;
                                    Status status = SPF.getStatus(token);
                                    if (status == Status.RED && (block = Block.add(token)) != null) {
                                        Server.logDebug("new BLOCK '" + block + "' added by '" + recipient
                                                + ";INEXISTENT'.");
                                        Peer.sendBlockToAll(block);
                                    }
                                    if (status != Status.GREEN && !Subnet.isValidIP(token)
                                            && (block = Block.addIfNotNull(user, token)) != null) {
                                        Server.logDebug("new BLOCK '" + block + "' added by '" + recipient
                                                + ";INEXISTENT'.");
                                    }
                                }
                                Analise.processToday(ip);
                                Analise.processToday(mx);
                                SPF.getTicket(client, user, ip, helo, hostname, sender, result, recipient,
                                        tokenSet, "INEXISTENT");
                                return "INEXISTENT\n";
                            }
                        } else if (Defer.count(fluxo) > Core.getFloodMaxRetry()) {
                            Analise.processToday(ip);
                            Analise.processToday(mx);
                            // A origem atingiu o limite de atraso 
                            // para liberao do destinatrio.
                            long time = System.currentTimeMillis();
                            Defer.end(fluxo);
                            Server.logDefer(time, fluxo, "DEFER FLOOD");
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "REJECT");
                            return "BLOCKED\n";
                        } else if (!result.equals("PASS") && !CacheHELO.match(ip, hostname, false)) {
                            // Bloquear automaticamente IP com reputao amarela.
                            if (SPF.isRed(ip)) {
                                if (Block.tryAdd(ip)) {
                                    Server.logDebug(
                                            "new BLOCK '" + ip + "' added by '" + recipient + ";INVALID'.");
                                }
                            }
                            Analise.processToday(ip);
                            SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                    tokenSet, "INVALID");
                            return "INVALID\n";
                        } else if (recipient != null && recipient.startsWith("postmaster@")) {
                            String url = Core.getURL();
                            String ticket = SPF.getTicket(client, user, ip, helo, hostname, sender, result,
                                    recipient, tokenSet, "ACCEPT");
                            return result + " "
                                    + (url == null ? ticket : url + URLEncoder.encode(ticket, "UTF-8")) + "\n";
                        } else if (result.equals("PASS")
                                && SPF.isGood(Provider.containsExact(mx) ? sender : mx)) {
                            // O remetente  vlido e tem excelente reputao,
                            // ainda que o provedor dele esteja com reputao ruim.
                            String url = Core.getURL();
                            String ticket = SPF.addQueryHam(client, user, ip, helo, hostname, sender, result,
                                    recipient, tokenSet, "ACCEPT");
                            return "PASS " + (url == null ? ticket : url + URLEncoder.encode(ticket, "UTF-8"))
                                    + "\n";
                        } else if (SPF.hasRed(tokenSet) || Analise.isCusterRED(ip, sender, hostname)) {
                            Analise.processToday(ip);
                            Analise.processToday(mx);
                            Action action = client == null ? Action.REJECT : client.getActionRED();
                            if (action == Action.REJECT) {
                                // Calcula frequencia de consultas.
                                SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                        tokenSet, "REJECT");
                                return "BLOCKED\n";
                            } else if (action == Action.DEFER) {
                                if (Defer.defer(fluxo, Core.getDeferTimeRED())) {
                                    String url = Core.getReleaseURL(fluxo);
                                    SPF.addQuery(client, user, ip, helo, hostname, sender, result, recipient,
                                            tokenSet, "LISTED");
                                    if (url == null || Defer.count(fluxo) > 1) {
                                        return "LISTED\n";
                                    } else if (result.equals("PASS")
                                            && enviarLiberacao(url, sender, recipient)) {
                                        // Envio da liberao por e-mail se 
                                        // houver validao do remetente por PASS.
                                        return "LISTED\n";
                                    } else {
                                        return "LISTED " + url + "\n";
                                    }
                                } else {
                                    // Calcula frequencia de consultas.
                                    SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result,
                                            recipient, tokenSet, "REJECT");
                                    return "BLOCKED\n";
                                }
                            } else if (action == Action.FLAG) {
                                String url = Core.getURL();
                                String ticket = SPF.getTicket(client, user, ip, helo, hostname, sender, result,
                                        recipient, tokenSet, "FLAG");
                                return "FLAG " + (url == null ? ticket : url + ticket) + "\n";
                            } else if (action == Action.HOLD) {
                                String url = Core.getURL();
                                String ticket = SPF.getTicket(client, user, ip, helo, hostname, sender, result,
                                        recipient, tokenSet, "HOLD");
                                return "HOLD " + (url == null ? ticket : url + ticket) + "\n";
                            } else {
                                return "ERROR: UNDEFINED ACTION\n";
                            }
                        } else if (Domain.isGraceTime(sender) || Domain.isGraceTime(hostname)) {
                            Server.logTrace("domain in grace time.");
                            for (String token : tokenSet) {
                                String block;
                                Status status = SPF.getStatus(token);
                                if (status == Status.RED && (block = Block.add(token)) != null) {
                                    Server.logDebug("new BLOCK '" + block + "' added by '" + status + "'.");
                                    Peer.sendBlockToAll(block);
                                }
                                if (status != Status.GREEN && !Subnet.isValidIP(token)
                                        && (block = Block.addIfNotNull(user, token)) != null) {
                                    Server.logDebug("new BLOCK '" + block + "' added by '" + status + "'.");
                                }
                            }
                            Analise.processToday(ip);
                            Analise.processToday(mx);
                            Action action = client == null ? Action.REJECT : client.getActionGRACE();
                            if (action == Action.REJECT) {
                                // Calcula frequencia de consultas.
                                SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result, recipient,
                                        tokenSet, "REJECT");
                                return "BLOCKED\n";
                            } else if (action == Action.DEFER) {
                                if (Defer.defer(fluxo, Core.getDeferTimeRED())) {
                                    String url = Core.getReleaseURL(fluxo);
                                    SPF.addQuery(client, user, ip, helo, hostname, sender, result, recipient,
                                            tokenSet, "LISTED");
                                    if (url == null || Defer.count(fluxo) > 1) {
                                        return "LISTED\n";
                                    } else if (result.equals("PASS")
                                            && enviarLiberacao(url, sender, recipient)) {
                                        // Envio da liberao por e-mail se 
                                        // houver validao do remetente por PASS.
                                        return "LISTED\n";
                                    } else {
                                        return "LISTED " + url + "\n";
                                    }
                                } else {
                                    // Calcula frequencia de consultas.
                                    SPF.addQuerySpam(client, user, ip, helo, hostname, sender, result,
                                            recipient, tokenSet, "REJECT");
                                    return "BLOCKED\n";
                                }
                            } else if (action == Action.FLAG) {
                                String url = Core.getURL();
                                String ticket = SPF.getTicket(client, user, ip, helo, hostname, sender, result,
                                        recipient, tokenSet, "FLAG");
                                return "FLAG " + (url == null ? ticket : url + ticket) + "\n";
                            } else if (action == Action.HOLD) {
                                String url = Core.getURL();
                                String ticket = SPF.getTicket(client, user, ip, helo, hostname, sender, result,
                                        recipient, tokenSet, "HOLD");
                                return "HOLD " + (url == null ? ticket : url + ticket) + "\n";
                            } else {
                                return "ERROR: UNDEFINED ACTION\n";
                            }
                        } else if (SPF.hasYellow(tokenSet) && Defer.defer(fluxo, Core.getDeferTimeYELLOW())) {
                            Analise.processToday(ip);
                            Analise.processToday(mx);
                            Action action = client == null ? Action.DEFER : client.getActionYELLOW();
                            if (action == Action.DEFER) {
                                // Pelo menos um identificador do conjunto est em greylisting com atrazo de 10min.
                                SPF.addQuery(client, user, ip, helo, hostname, sender, result, recipient,
                                        tokenSet, "GREYLIST");
                                return "GREYLIST\n";
                            } else if (action == Action.HOLD) {
                                String url = Core.getURL();
                                String ticket = SPF.getTicket(client, user, ip, helo, hostname, sender, result,
                                        recipient, tokenSet, "HOLD");
                                return "HOLD " + (url == null ? ticket : url + ticket) + "\n";
                            } else {
                                return "ERROR: UNDEFINED ACTION\n";
                            }
                        } else if (SPF.isFlood(tokenSet) && !Provider.containsHELO(ip, hostname)
                                && Defer.defer(origem, Core.getDeferTimeFLOOD())) {
                            Analise.processToday(ip);
                            Analise.processToday(mx);
                            // Pelo menos um identificador est com frequncia superior ao permitido.
                            Server.logDebug("FLOOD " + tokenSet);
                            SPF.addQuery(client, user, ip, helo, hostname, sender, result, recipient, tokenSet,
                                    "GREYLIST");
                            return "GREYLIST\n";
                        } else if (result.equals("SOFTFAIL") && !Provider.containsHELO(ip, hostname)
                                && Defer.defer(fluxo, Core.getDeferTimeSOFTFAIL())) {
                            Analise.processToday(ip);
                            Analise.processToday(mx);
                            // SOFTFAIL com atrazo de 1min.
                            SPF.addQuery(client, user, ip, helo, hostname, sender, result, recipient, tokenSet,
                                    "GREYLIST");
                            return "GREYLIST\n";
                        } else {
                            Analise.processToday(ip);
                            Analise.processToday(mx);
                            // Calcula frequencia de consultas.
                            String url = Core.getURL();
                            String ticket = SPF.addQueryHam(client, user, ip, helo, hostname, sender, result,
                                    recipient, tokenSet, "ACCEPT");
                            return result + " "
                                    + (url == null ? ticket : url + URLEncoder.encode(ticket, "UTF-8")) + "\n";
                        }
                    }
                } catch (ProcessException ex) {
                    if (ex.isErrorMessage("HOST NOT FOUND")) {
                        return "NXDOMAIN\n";
                    } else {
                        throw ex;
                    }
                }
            } else {
                return "INVALID QUERY\n";
            }
        }
        return result;
    } catch (ProcessException ex) {
        Server.logError(ex);
        return ex.getMessage() + "\n";
    } catch (Exception ex) {
        Server.logError(ex);
        return "ERROR: FATAL\n";
    }
}

From source file:org.dasein.cloud.cloudsigma.compute.vm.ServerSupport.java

private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject object)
        throws CloudException, InternalException {
    if (object == null) {
        return null;
    }//from w w  w  .j  a  v  a2 s.c o  m
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new NoContextException();
    }
    String regionId = ctx.getRegionId();

    if (regionId == null) {
        throw new CloudSigmaConfigurationException("No region was specified for this request");
    }
    VirtualMachine vm = new VirtualMachine();

    vm.setPersistent(true);
    vm.setCurrentState(VmState.PENDING);
    vm.setImagable(false);
    vm.setPausable(false);
    vm.setRebootable(false);
    vm.setPlatform(Platform.UNKNOWN);
    vm.setProviderDataCenterId(regionId + "-a");
    vm.setProviderRegionId(regionId);
    vm.setArchitecture(Architecture.I64);
    try {
        String id = object.getString("uuid");

        vm.setProviderVirtualMachineId(id);
        //dmayne 20130218: use JSON Parsing
        String imageId = "";
        JSONArray drives = null;
        if (object.has("drives")) {
            drives = object.getJSONArray("drives");
            for (int i = 0; i < drives.length(); i++) {
                JSONObject jdrive = drives.getJSONObject(i);
                if (jdrive.has("boot_order")) {
                    String boot_order = jdrive.getString("boot_order");
                    if (boot_order.equals("1")) {
                        JSONObject driveTag = jdrive.getJSONObject("drive");
                        imageId = driveTag.getString("uuid");
                        break;
                    }
                }
            }
        }
        if (imageId != null && !imageId.equals("")) {
            vm.setProviderMachineImageId(imageId);

            //dmayne 20130524: try to get image os
            logger.debug("Trying to establish the platform for " + imageId);
            MachineImage image = provider.getComputeServices().getImageSupport().getImage(imageId);
            Platform os = image.getPlatform();
            vm.setPlatform(os);
            logger.debug("Server os is " + vm.getPlatform());
        }

        String vlanId = null;
        JSONArray nics = null;
        if (object.has("nics")) {
            nics = object.getJSONArray("nics");
            for (int i = 0; i < nics.length(); i++) {
                JSONObject jnic = nics.getJSONObject(i);
                if (jnic.has("vlan") && !jnic.isNull("vlan")) {
                    JSONObject vlan = jnic.getJSONObject("vlan");
                    if (vlan != null) {
                        vlanId = vlan.getString("uuid");
                        break;
                    }
                }
            }
        }
        if (vlanId != null) {
            vm.setProviderVlanId(vlanId);
        }

        if (drives != null) {
            for (int i = 0; i < drives.length(); i++) {
                JSONObject jDrive = drives.getJSONObject(i);
                String devChannel = jDrive.getString("dev_channel");
                JSONObject driveTag = jDrive.getJSONObject("drive");
                String value = driveTag.getString("uuid");
                if (value != null) {
                    String key = "virtio" + ":" + devChannel;
                    vm.setTag(key, value);
                }
            }
        }

        TreeSet<String> allIps = new TreeSet<String>();
        ArrayList<String> firewallIds = new ArrayList<String>();
        if (nics != null) {
            for (int i = 0; i < nics.length(); i++) {
                //todo:dmayne 20130218: will a server ever have both ipv4 and ipv6?
                JSONObject jnic = nics.getJSONObject(i);

                if (jnic.has("ip_v4_conf") && !jnic.isNull("ip_v4_conf")) {
                    JSONObject ipv4 = jnic.getJSONObject("ip_v4_conf");
                    if (ipv4 != null) {
                        String ip4 = null;
                        if (ipv4.has("ip") && !ipv4.isNull("ip")) {
                            JSONObject ipObj = ipv4.getJSONObject("ip");
                            if (ipObj != null) {
                                ip4 = ipObj.getString("uuid");
                                if (ip4 != null && (!ip4.equalsIgnoreCase(""))) {
                                    allIps.add(ip4);
                                }
                            }
                        }
                        if (ipv4.has("conf")) {
                            String conf4 = ipv4.getString("conf");
                            if (conf4.equalsIgnoreCase("static")) {
                                if (ip4 != null && !ip4.equals("") && !ip4.equals("auto")) {
                                    if (vm.getProviderAssignedIpAddressId() == null) {
                                        vm.setProviderAssignedIpAddressId(ip4);
                                    }
                                }
                            }
                        }
                    }
                }

                if (jnic.has("ip_v6_conf") && !jnic.isNull("ip_v6_conf")) {
                    JSONObject ipv6 = jnic.getJSONObject("ip_v6_conf");
                    if (ipv6 != null) {
                        String ip6 = null;
                        if (ipv6.has("ip") && !ipv6.isNull("ip")) {
                            JSONObject ip6Obj = ipv6.getJSONObject("ip");
                            if (ip6Obj != null) {
                                ip6 = ip6Obj.getString("uuid");
                                if (ip6 != null && (!ip6.equalsIgnoreCase(""))) {
                                    allIps.add(ip6);
                                }
                            }
                        }
                        if (ipv6.has("conf")) {
                            String conf6 = ipv6.getString("conf");
                            if (conf6.equalsIgnoreCase("static")) {
                                if (ip6 != null && !ip6.equals("") && !ip6.equals("auto")) {
                                    if (vm.getProviderAssignedIpAddressId() == null) {
                                        vm.setProviderAssignedIpAddressId(ip6);
                                    }
                                }
                            }
                        }
                    }
                }

                //dmayne 20130524: check for runtime details to get dhcp ip address
                logger.debug("Trying to get runtime ip info");
                if (jnic.has("runtime") && !jnic.isNull("runtime")) {
                    JSONObject jRun = jnic.getJSONObject("runtime");
                    if (jRun.has("ip_v4") && !jRun.isNull("ip_v4")) {
                        JSONObject ipRun = jRun.getJSONObject("ip_v4");
                        String ip = ipRun.getString("uuid");
                        if (ip != null && (!ip.equalsIgnoreCase(""))) {
                            allIps.add(ip);
                        }
                    }
                    if (jRun.has("ip_v6") && !jRun.isNull("ip_v6")) {
                        JSONObject ipRun = jRun.getJSONObject("ip_v6");
                        String ip = ipRun.getString("uuid");
                        if (ip != null && (!ip.equalsIgnoreCase(""))) {
                            allIps.add(ip);
                        }
                    }
                }

                //check for firewall policy
                if (jnic.has("firewall_policy") && !jnic.isNull("firewall_policy")) {
                    JSONObject fw = jnic.getJSONObject("firewall_policy");
                    if (fw.has("uuid") && !fw.isNull("uuid")) {
                        String firewall = fw.getString("uuid");
                        logger.debug("adding firewall policy " + firewall + " to server "
                                + vm.getProviderVirtualMachineId());
                        firewallIds.add(firewall);
                    }
                }
            }
        }
        if (!allIps.isEmpty()) {
            setIP(vm, allIps);
        }

        if (!firewallIds.isEmpty()) {
            String[] vmFirewalls = new String[firewallIds.size()];
            for (int i = 0; i < firewallIds.size(); i++) {
                vmFirewalls[i] = firewallIds.get(i);
            }
            vm.setProviderFirewallIds(vmFirewalls);
        }

        JSONObject owner = object.getJSONObject("owner");
        String user = owner.getString("uuid");
        vm.setProviderOwnerId(user);

        String value = object.getString("name");
        vm.setName(value);

        JSONObject meta = object.getJSONObject("meta");
        if (meta != null && meta.has("description")) {
            String description = meta.getString("description");
            if (description != null && !description.equals("")) {
                vm.setDescription(description);
            }
        }

        value = object.getString("vnc_password");
        vm.setRootUser("root");
        vm.setRootPassword(value);

        String status = object.getString("status");
        if (status != null) {
            if (status.equalsIgnoreCase("stopped")) {
                vm.setCurrentState(VmState.STOPPED);
                vm.setImagable(true);
            } else if (status.equalsIgnoreCase("stopping")) {
                vm.setCurrentState(VmState.STOPPING);
            } else if (status.equalsIgnoreCase("started") || status.equalsIgnoreCase("running")) {
                vm.setCurrentState(VmState.RUNNING);
            } else if (status.equalsIgnoreCase("paused")) {
                vm.setCurrentState(VmState.PAUSED);
            } else if (status.equalsIgnoreCase("dead") || status.equalsIgnoreCase("dumped")
                    || status.equalsIgnoreCase("unavailable")) {
                vm.setCurrentState(VmState.TERMINATED);
            } else if (status.startsWith("imaging")) {
                vm.setCurrentState(VmState.PENDING);
            } else {
                logger.warn("DEBUG: Unknown CloudSigma server status: " + status);
            }
        } else {
            vm.setCurrentState(VmState.PENDING);
        }

        String cpuCount = "1", cpuSpeed = "1000", ramInMB = "512", ramInBytes = "0";

        try {
            String tmp = object.getString("smp");
            if (tmp != null) {
                cpuCount = String.valueOf(Integer.parseInt(tmp));
            }
        } catch (NumberFormatException ignore) {
            // ignore
        }
        try {
            String tmp = object.getString("cpu");
            if (tmp != null) {
                cpuSpeed = String.valueOf(Integer.parseInt(tmp));
            }
            // we will be given total cpu speed but we need cpuPerSMP
            cpuSpeed = String.valueOf(Integer.parseInt(cpuSpeed) / Integer.parseInt(cpuCount));
        } catch (NumberFormatException ignore) {
            // ignore
        }
        try {
            String tmp = object.getString("mem");
            if (tmp != null) {
                ramInBytes = String.valueOf(Long.parseLong(tmp));
                ramInMB = String.valueOf(Long.parseLong(ramInBytes) / 1024 / 1024);
            }
        } catch (NumberFormatException ignore) {
            // ignore
        }
        if (cpuCount.equals("1")) {
            vm.setProductId(ramInMB + ":" + cpuSpeed);
        } else {
            vm.setProductId(ramInMB + ":" + cpuSpeed + ":" + cpuCount);
        }
        if (vm.getProviderVirtualMachineId() == null) {
            return null;
        }
        if (vm.getName() == null) {
            vm.setName(vm.getProviderVirtualMachineId());
        }
        if (vm.getDescription() == null) {
            vm.setDescription(vm.getName());
        }
        vm.setClonable(VmState.PAUSED.equals(vm.getCurrentState()));
        return vm;
    } catch (JSONException e) {
        throw new InternalException(e);
    }
}

From source file:net.spfbl.http.ServerHTTP.java

@SuppressWarnings("unchecked")
private static HashMap<String, Object> getParameterMap(String query) throws UnsupportedEncodingException {
    if (query == null) {
        return new HashMap<String, Object>();
    } else {//from   w  w w.  j ava 2s  . c  o  m
        Integer otp = null;
        Long begin = null;
        TreeSet<String> identifierSet = new TreeSet<String>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        String pairs[] = query.split("[&]");
        for (String pair : pairs) {
            String param[] = pair.split("[=]");
            String key = null;
            String value = null;
            if (param.length > 0) {
                key = URLDecoder.decode(param[0], System.getProperty("file.encoding"));
            }
            if (param.length > 1) {
                value = URLDecoder.decode(param[1], System.getProperty("file.encoding"));
            }
            if ("identifier".equals(key)) {
                identifierSet.add(value);
            } else if ("otp".equals(key)) {
                try {
                    otp = Integer.parseInt(value);
                } catch (NumberFormatException ex) {
                    // Ignore.
                }
            } else if ("begin".equals(key)) {
                try {
                    begin = Long.parseLong(value);
                } catch (NumberFormatException ex) {
                    // Ignore.
                }
            } else if ("filter".equals(key)) {
                if (value == null) {
                    map.put(key, "");
                } else {
                    value = Core.removerAcentuacao(value);
                    value = value.replace(" ", "");
                    value = value.toLowerCase();
                    if (value.length() > 0) {
                        map.put(key, value);
                    }
                }
            } else {
                map.put(key, value);
            }
        }
        if (otp != null) {
            map.put("otp", otp);
        }
        if (begin != null) {
            map.put("begin", begin);
        }
        if (!identifierSet.isEmpty()) {
            map.put("identifier", identifierSet);
        }
        return map;
    }
}

From source file:com.eucalyptus.walrus.WalrusFSManager.java

@Override
public ListBucketResponseType listBucket(ListBucketType request) throws WalrusException {
    ListBucketResponseType reply = (ListBucketResponseType) request.getReply();

    EntityWrapper<BucketInfo> db = EntityWrapper.get(BucketInfo.class);

    try {//from   w ww.  j  av a2 s .co  m
        String bucketName = request.getBucket();
        BucketInfo bucketInfo = new BucketInfo(bucketName);
        bucketInfo.setHidden(false);
        List<BucketInfo> bucketList = db.queryEscape(bucketInfo);

        Context ctx = Contexts.lookup();
        Account account = ctx.getAccount();

        int maxKeys = -1;
        String maxKeysString = request.getMaxKeys();
        if (maxKeysString != null) {
            maxKeys = Integer.parseInt(maxKeysString);
            if (maxKeys < 0) {
                throw new InvalidArgumentException("max-keys",
                        "Argument max-keys must be an integer between 0 and " + Integer.MAX_VALUE);
            }
        } else {
            maxKeys = WalrusProperties.MAX_KEYS;
        }

        if (bucketList.size() > 0) {
            BucketInfo bucket = bucketList.get(0);
            BucketLogData logData = bucket.getLoggingEnabled() ? request.getLogData() : null;
            if (logData != null) {
                updateLogData(bucket, logData);
                reply.setLogData(logData);
            }

            if (Contexts.lookup().hasAdministrativePrivileges()) {
                try {
                    if (bucketHasSnapshots(bucketName)) {
                        db.rollback();
                        throw new NoSuchBucketException(bucketName);
                    }
                } catch (Exception e) {
                    db.rollback();
                    throw new InternalErrorException(e);
                }
            }

            String prefix = request.getPrefix();
            String delimiter = request.getDelimiter();
            String marker = request.getMarker();

            reply.setName(bucketName);
            reply.setIsTruncated(false);
            reply.setPrefix(prefix);
            reply.setMarker(marker);
            reply.setDelimiter(delimiter);
            reply.setMaxKeys(maxKeys);

            if (maxKeys == 0) {
                // No keys requested, so just return
                reply.setContents(new ArrayList<ListEntry>());
                reply.setCommonPrefixesList(new ArrayList<CommonPrefixesEntry>());
                db.commit();
                return reply;
            }

            final int queryStrideSize = maxKeys + 1;
            EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class);

            ObjectInfo searchObj = new ObjectInfo();
            searchObj.setBucketName(bucketName);
            searchObj.setLast(true);
            searchObj.setDeleted(false);

            Criteria objCriteria = dbObject.createCriteria(ObjectInfo.class);
            objCriteria.add(Example.create(searchObj));
            objCriteria.addOrder(Order.asc("objectKey"));
            objCriteria.setMaxResults(queryStrideSize); // add one to, hopefully, indicate truncation in one call

            if (!Strings.isNullOrEmpty(marker)) {
                // The result set should be exclusive of the marker. marker could be a common prefix from a previous response. Look for keys that
                // lexicographically follow the marker and don't contain the marker as the prefix.
                objCriteria.add(Restrictions.gt("objectKey", marker));
            } else {
                marker = "";
            }

            if (!Strings.isNullOrEmpty(prefix)) {
                objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START));
            } else {
                prefix = "";
            }

            // Ensure not null.
            if (Strings.isNullOrEmpty(delimiter)) {
                delimiter = "";
            }

            List<ObjectInfo> objectInfos = null;
            int resultKeyCount = 0;
            ArrayList<ListEntry> contents = new ArrayList<ListEntry>(); // contents for reply
            String nextMarker = null;
            TreeSet<String> commonPrefixes = new TreeSet<String>();
            int firstResult = -1;

            // Iterate over result sets of size maxkeys + 1
            do {
                // Start listing from the 0th element and increment the first element to be listed by the query size
                objCriteria.setFirstResult(queryStrideSize * (++firstResult));
                objectInfos = (List<ObjectInfo>) objCriteria.list();

                if (objectInfos.size() > 0) {
                    for (ObjectInfo objectInfo : objectInfos) {
                        String objectKey = objectInfo.getObjectKey();

                        // Check if it will get aggregated as a commonprefix
                        if (!Strings.isNullOrEmpty(delimiter)) {
                            String[] parts = objectKey.substring(prefix.length()).split(delimiter);
                            if (parts.length > 1) {
                                String prefixString = prefix + parts[0] + delimiter;
                                if (!StringUtils.equals(prefixString, marker)
                                        && !commonPrefixes.contains(prefixString)) {
                                    if (resultKeyCount == maxKeys) {
                                        // This is a new record, so we know we're truncating if this is true
                                        reply.setNextMarker(nextMarker);
                                        reply.setIsTruncated(true);
                                        resultKeyCount++;
                                        break;
                                    }

                                    commonPrefixes.add(prefixString);
                                    resultKeyCount++; // count the unique commonprefix as a single return entry

                                    // If max keys have been collected, set the next-marker. It might be needed for the response if the list is
                                    // truncated
                                    // If the common prefixes hit the limit set by max-keys, next-marker is the last common prefix
                                    if (resultKeyCount == maxKeys) {
                                        nextMarker = prefixString;
                                    }
                                }
                                continue;
                            }
                        }

                        if (resultKeyCount == maxKeys) {
                            // This is a new (non-commonprefix) record, so we know we're truncating
                            reply.setNextMarker(nextMarker);
                            reply.setIsTruncated(true);
                            resultKeyCount++;
                            break;
                        }

                        // Process the entry as a full key listing
                        ListEntry listEntry = new ListEntry();
                        listEntry.setKey(objectKey);
                        listEntry.setEtag(objectInfo.getEtag());
                        listEntry.setLastModified(
                                DateFormatter.dateToListingFormattedString(objectInfo.getLastModified()));
                        listEntry.setStorageClass(objectInfo.getStorageClass());
                        listEntry.setSize(objectInfo.getSize());
                        listEntry.setStorageClass(objectInfo.getStorageClass());
                        try {
                            Account ownerAccount = Accounts.lookupAccountById(objectInfo.getOwnerId());
                            listEntry.setOwner(
                                    new CanonicalUser(ownerAccount.getCanonicalId(), ownerAccount.getName()));
                        } catch (AuthException e) {
                            db.rollback();
                            throw new AccessDeniedException("Bucket", bucketName, logData);
                        }
                        contents.add(listEntry);

                        resultKeyCount++;

                        // If max keys have been collected, set the next-marker. It might be needed for the response if the list is truncated
                        if (resultKeyCount == maxKeys) {
                            nextMarker = objectKey;
                        }
                    }
                }

                if (resultKeyCount <= maxKeys && objectInfos.size() <= maxKeys) {
                    break;
                }
            } while (resultKeyCount <= maxKeys);

            reply.setContents(contents);

            // Prefixes are already sorted, add them to the proper data structures and populate the reply
            if (!commonPrefixes.isEmpty()) {
                ArrayList<CommonPrefixesEntry> commonPrefixesList = new ArrayList<CommonPrefixesEntry>();
                for (String prefixEntry : commonPrefixes) {
                    commonPrefixesList.add(new CommonPrefixesEntry(prefixEntry));
                }
                reply.setCommonPrefixesList(commonPrefixesList);
            }
        } else {
            db.rollback();
            throw new NoSuchBucketException(bucketName);
        }
        db.commit();
        return reply;
    } finally {
        if (db.isActive()) {
            db.rollback();
        }
    }
}