Example usage for java.util SortedMap get

List of usage examples for java.util SortedMap get

Introduction

In this page you can find the example usage for java.util SortedMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:eus.ixa.ixa.pipe.convert.AbsaSemEval.java

public static String absa2015Toabsa2015AnotatedWithMultipleDocClasModels(String fileName, String modelsList) {
    //reading the ABSA xml file
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    Document doc = null;//  www .  j  a v  a 2 s . c o m
    try {
        doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);

        int cantSent = 0;

        for (Element sent : sentences) {

            Element opinionsElement = sent.getChild("Opinions");
            if (opinionsElement != null) {
                //iterating over every opinion in the opinions element
                List<Element> opinionList = opinionsElement.getChildren();
                for (int i = opinionList.size() - 1; i >= 0; i--) {
                    Element opinion = opinionList.get(i);
                    opinionsElement.removeContent(opinion);
                }
            }

            KAFDocument kaf;
            final String lang = "en";
            final String kafVersion = "1.0";
            kaf = new KAFDocument(lang, kafVersion);
            final Properties properties = new Properties();
            properties.setProperty("language", lang);
            properties.setProperty("normalize", "default");
            properties.setProperty("untokenizable", "no");
            properties.setProperty("hardParagraph", "no");
            InputStream inputStream = new ByteArrayInputStream(
                    sent.getChildText("text").getBytes(Charset.forName("UTF-8")));
            BufferedReader breader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            final eus.ixa.ixa.pipe.tok.Annotate annotator = new eus.ixa.ixa.pipe.tok.Annotate(breader,
                    properties);
            annotator.tokenizeToKAF(kaf);

            //System.err.println(kaf.toString());

            BufferedReader reader = new BufferedReader(new FileReader(modelsList));
            int lines = 0;
            while (reader.readLine() != null)
                lines++;
            reader.close();

            boolean Binary = false;
            if (lines > 1)
                Binary = true;

            File file = new File(modelsList);
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                //System.err.println("-" + line + "-" + kaf.getLang());

                /*
                File fileTmp = new File(line);
                String fileTmp0 = Paths.get(".").toAbsolutePath().normalize().toString()+"/tmpModels/"+line+"."+cantSent;
                File fileTmp2 = new File(fileTmp0);
                Files.copy(fileTmp.toPath(), fileTmp2.toPath());
                */
                Properties oteProperties = new Properties();
                oteProperties.setProperty("model", line);
                oteProperties.setProperty("language", kaf.getLang());
                oteProperties.setProperty("clearFeatures", "no");

                //eus.ixa.ixa.pipe.doc.Annotate docClassifier = new eus.ixa.ixa.pipe.doc.Annotate(oteProperties);
                //docClassifier.classify(kaf);

                StatisticalDocumentClassifier docClassifier = new StatisticalDocumentClassifier(oteProperties);
                String source = oteProperties.getProperty("model");

                List<List<WF>> sentences0 = kaf.getSentences();
                List<String> tokens = new ArrayList<>();
                for (List<WF> sentence : sentences0) {
                    for (WF wf : sentence) {
                        tokens.add(wf.getForm());
                    }
                }
                String[] document = tokens.toArray(new String[tokens.size()]);
                String label = docClassifier.classify(document);
                //Topic topic = kaf.newTopic(label);
                double[] probs = docClassifier.classifyProb(document);
                //topic.setConfidence((float) probs[0]);
                //topic.setSource(Paths.get(source).getFileName().toString());
                //topic.setMethod("ixa-pipe-doc");

                SortedMap<Double, String> map = new TreeMap<Double, String>(Collections.reverseOrder());

                //System.err.println("RESULTADO: " + docClassifier.getClassifierME().getAllLabels(probs));
                System.err.println("SENTENCE:" + sent.getChildText("text"));
                Double sum = 0.0;
                for (int i = 0; i < probs.length; i++) {
                    //System.err.println("RESULTADO: " + docClassifier.getClassifierME().getLabel(i) + "\t\t" + probs[i]);
                    sum += probs[i];

                    map.put(probs[i], docClassifier.getClassifierME().getLabel(i));

                    //System.err.println("\t\tPUT: " + probs[i] + " -- " + docClassifier.getClassifierME().getLabel(i));

                    //Topic topic = kaf.newTopic(docClassifier.getClassifierME().getLabel(i));
                    //topic.setConfidence((float) probs[i]);
                    //topic.setSource(Paths.get(source).getFileName().toString());
                    //topic.setMethod("ixa-pipe-doc");
                }
                sum = sum / probs.length;
                System.err.println("MEDIA: " + sum);

                Set<Double> Keys = map.keySet();

                boolean first = true;
                for (Double key : Keys) {
                    System.err.println("\t\t" + key + "\t" + map.get(key));
                    if (Binary) {
                        if (key >= 0.40) {
                            Topic topic = kaf.newTopic(map.get(key));
                            topic.setConfidence((float) key.floatValue());
                            topic.setSource(Paths.get(source).getFileName().toString());
                            topic.setMethod("ixa-pipe-doc");
                        }
                        break;
                    } else {
                        if (first) {
                            first = false;
                            /*if (key > 0.65 || (key < 0.20 && key > 0.10)) {
                               Topic topic = kaf.newTopic(map.get(key));
                               topic.setConfidence((float) key.floatValue());
                               topic.setSource(Paths.get(source).getFileName().toString());
                               topic.setMethod("ixa-pipe-doc");
                               //break;
                            }
                            else */
                            if (key < 0.10) {
                                break;
                            } else {
                                Topic topic = kaf.newTopic(map.get(key));
                                topic.setConfidence((float) key.floatValue());
                                topic.setSource(Paths.get(source).getFileName().toString());
                                topic.setMethod("ixa-pipe-doc");
                            }
                        } else if (key > 0.25) {
                            Topic topic = kaf.newTopic(map.get(key));
                            topic.setConfidence((float) key.floatValue());
                            topic.setSource(Paths.get(source).getFileName().toString());
                            topic.setMethod("ixa-pipe-doc");
                        }
                    }

                }

                //Files.delete(fileTmp2.toPath());
            }
            fileReader.close();

            //System.err.println(kaf.toString());
            cantSent++;

            System.err.println("IsBinary: " + Binary);

            List<Topic> topicList = kaf.getTopics();
            for (Topic topic : topicList) {
                //System.err.println(topic.getTopicValue());
                if (!topic.getTopicValue().equals("NO")) {
                    Element opinionElem = new Element("Opinion");
                    opinionElem.setAttribute("target", "na");
                    opinionElem.setAttribute("category", topic.getTopicValue());
                    //TODO we still do not have polarity here
                    opinionElem.setAttribute("polarity", String.valueOf(topic.getConfidence()));
                    opinionElem.setAttribute("from", "0");
                    opinionElem.setAttribute("to", "0");
                    opinionsElement.addContent(opinionElem);
                }
            }

        } //end of sentence
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }

    XMLOutputter xmlOutput = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    xmlOutput.setFormat(format);
    return xmlOutput.outputString(doc);
}

From source file:com.aurel.track.report.dashboard.BurnDownChart.java

public SortedMap<Integer, SortedMap<Integer, Double>> calculatePlannedValuesDependingOnEffortType(
        Date minStartDate, Date maxEndDate, Integer timeInterval, Integer selectedEffortType) {

    SortedMap<Integer, SortedMap<Integer, Double>> yearToIntervalToPlannedValue = new TreeMap<Integer, SortedMap<Integer, Double>>();
    if (reportBeanWithHistoryList != null) {
        Calendar calendarStartDate = Calendar.getInstance();
        Calendar calendarEndDate = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        //to avoid that the last days of the year to be taken as the first
        //week of the now year but the year remains the old one
        int calendarInterval = EarnedValueDatasource.getCalendarInterval(timeInterval);
        for (ReportBean reportBean : reportBeanWithHistoryList) {
            TWorkItemBean workItemBean = reportBean.getWorkItemBean();
            Date startDate = workItemBean.getStartDate();
            Date endDate = workItemBean.getEndDate();
            if (startDate == null || endDate == null) {
                continue;
            }/* w  w  w .j  av a  2s.c  o m*/

            calendarStartDate.setTime(dateFrom);
            calendarEndDate.setTime(dateTo);
            calendar.setTime(dateFrom);
            int yearValue = calendarStartDate.get(Calendar.YEAR);
            int intervalValue = calendarStartDate.get(calendarInterval);
            boolean isFirst = true;
            while (calendar.before(calendarEndDate) || isFirst) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    calendar.add(calendarInterval, 1);
                }
                yearValue = calendar.get(Calendar.YEAR);
                intervalValue = calendar.get(calendarInterval);
                SortedMap<Integer, Double> intervalToPlannedValues = yearToIntervalToPlannedValue
                        .get(Integer.valueOf(yearValue));
                if (intervalToPlannedValues == null) {
                    yearToIntervalToPlannedValue.put(new Integer(yearValue), new TreeMap<Integer, Double>());
                    intervalToPlannedValues = yearToIntervalToPlannedValue.get(Integer.valueOf(yearValue));
                }
                Double totalPlannedValueForInterval = intervalToPlannedValues
                        .get(Integer.valueOf(intervalValue));
                if (totalPlannedValueForInterval == null) {
                    totalPlannedValueForInterval = 0.0;
                }
                if (DateTimeUtils.less(calendar.getTime(), endDate)) {
                    if (selectedEffortType == EFFORT_TYPE.NR_OF_ITEMS_IN_INTERVAL) {
                        totalPlannedValueForInterval += 1.0;
                    } else {
                        Integer storyPointValueID = getStoryPointValueID(workItemBean,
                                customFieldIDForStoryPoint);
                        if (storyPointValueID != null) {
                            Integer storyPointValue = storyPointValueIDToValueMap.get(storyPointValueID);
                            if (storyPointValue != null) {
                                totalPlannedValueForInterval += storyPointValue;
                            }
                        }
                    }
                }
                intervalToPlannedValues.put(Integer.valueOf(intervalValue), totalPlannedValueForInterval);
            }
        }
    }
    return yearToIntervalToPlannedValue;
}

From source file:org.apache.hadoop.hbase.master.RegionManager.java

private void startCFAction(final byte[] regionName, final byte[] columnFamily, final HRegionInfo info,
        final HServerAddress server,
        final SortedMap<byte[], SortedMap<byte[], Pair<HRegionInfo, HServerAddress>>> map) {
    synchronized (map) {
        SortedMap<byte[], Pair<HRegionInfo, HServerAddress>> cfMap = map.get(regionName);
        if (cfMap == null) {
            cfMap = Collections.synchronizedSortedMap(
                    new TreeMap<byte[], Pair<HRegionInfo, HServerAddress>>(Bytes.BYTES_COMPARATOR));
        }//from  www. j  a  va 2s . c o  m
        cfMap.put(columnFamily, new Pair<HRegionInfo, HServerAddress>(info, server));
        map.put(regionName, cfMap);
    }
}

From source file:org.codehaus.mojo.license.ArtifactHelper.java

/**
 * Get the list of project dependencies after applying transitivity and filtering rules.
 * /* w w w.  j ava  2  s  .  c  o  m*/
 * @param mojo
 * @param log
 * @param cache
 * @return
 */
public static SortedMap<String, MavenProject> loadProjectDependencies(MavenProjectDependenciesLoader mojo,
        Log log, SortedMap<String, MavenProject> cache) {

    boolean haveNoIncludedGroups = StringUtils.isEmpty(mojo.getIncludedGroups());
    boolean haveNoIncludedArtifacts = StringUtils.isEmpty(mojo.getIncludedArtifacts());

    boolean haveExcludedGroups = StringUtils.isNotEmpty(mojo.getExcludedGroups());
    boolean haveExcludedArtifacts = StringUtils.isNotEmpty(mojo.getExcludedArtifacts());
    boolean haveExclusions = haveExcludedGroups || haveExcludedArtifacts;

    Pattern includedGroupPattern = null;
    Pattern includedArtifactPattern = null;
    Pattern excludedGroupPattern = null;
    Pattern excludedArtifactPattern = null;

    if (!haveNoIncludedGroups) {
        includedGroupPattern = Pattern.compile(mojo.getIncludedGroups());
    }
    if (!haveNoIncludedArtifacts) {
        includedArtifactPattern = Pattern.compile(mojo.getIncludedArtifacts());
    }
    if (haveExcludedGroups) {
        excludedGroupPattern = Pattern.compile(mojo.getExcludedGroups());
    }
    if (haveExcludedArtifacts) {
        excludedArtifactPattern = Pattern.compile(mojo.getExcludedArtifacts());
    }

    MavenProject project = mojo.getProject();

    Set<?> depArtifacts;

    if (mojo.isIncludeTransitiveDependencies()) {
        // All project dependencies
        depArtifacts = project.getArtifacts();
    } else {
        // Only direct project dependencies
        depArtifacts = project.getDependencyArtifacts();
    }

    ArtifactRepository localRepository = mojo.getLocalRepository();
    List remoteRepositories = mojo.getRemoteRepositories();
    MavenProjectBuilder projectBuilder = mojo.getMavenProjectBuilder();

    List<String> excludeScopes = mojo.getExcludeScopes();

    boolean verbose = mojo.isVerbose();

    SortedMap<String, MavenProject> result = new TreeMap<String, MavenProject>();

    for (Object o : depArtifacts) {
        Artifact artifact = (Artifact) o;

        if (excludeScopes.contains(artifact.getScope())) {

            // never treate system artifacts (they are mysterious and
            // no information can be retrive from anywhere)...
            continue;
        }

        String id = getArtifactId(artifact);

        if (verbose) {
            log.info("detected artifact " + id);
        }

        // Check if the project should be included
        // If there is no specified artifacts and group to include, include all
        boolean isToInclude = haveNoIncludedArtifacts && haveNoIncludedGroups
                || isIncludable(log, artifact, includedGroupPattern, includedArtifactPattern);

        // Check if the project should be excluded
        boolean isToExclude = isToInclude && haveExclusions
                && isExcludable(log, artifact, excludedGroupPattern, excludedArtifactPattern);

        if (!isToInclude || isToExclude) {
            if (verbose) {
                log.info("skip artifact " + id);
            }
            continue;
        }

        MavenProject depMavenProject = null;

        if (cache != null) {

            // try to get project from cache
            depMavenProject = cache.get(id);
        }

        if (depMavenProject != null) {
            if (verbose) {
                log.info("add dependency [" + id + "] (from cache)");
            }
        } else {

            // build project

            try {
                depMavenProject = projectBuilder.buildFromRepository(artifact, remoteRepositories,
                        localRepository, true);
            } catch (ProjectBuildingException e) {
                log.warn("Unable to obtain POM for artifact : " + artifact);
                log.warn(e);
                continue;
            }

            if (verbose) {
                log.info("add dependency [" + id + "]");
            }
            if (cache != null) {

                // store it also in cache
                cache.put(id, depMavenProject);
            }
        }

        // keep the project
        result.put(id, depMavenProject);
    }

    return result;
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleListParts(HttpServletRequest request, HttpServletResponse response, BlobStore blobStore,
        String containerName, String blobName, String uploadId) throws IOException, S3Exception {
    // support only the no-op zero case
    String partNumberMarker = request.getParameter("part-number-marker");
    if (partNumberMarker != null && !partNumberMarker.equals("0")) {
        throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
    }//from  ww w.  j  ava2  s  . c o m

    // TODO: how to reconstruct original mpu?
    MultipartUpload mpu = MultipartUpload.create(containerName, blobName, uploadId,
            createFakeBlobMetadata(blobStore), new PutOptions());

    List<MultipartPart> parts;
    if (getBlobStoreType(blobStore).equals("azureblob")) {
        // map Azure subparts back into S3 parts
        SortedMap<Integer, Long> map = new TreeMap<>();
        for (MultipartPart part : blobStore.listMultipartUpload(mpu)) {
            int virtualPartNumber = part.partNumber() / 10_000;
            Long size = map.get(virtualPartNumber);
            map.put(virtualPartNumber, (size == null ? 0L : (long) size) + part.partSize());
        }
        parts = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : map.entrySet()) {
            String eTag = ""; // TODO: bogus value
            Date lastModified = null; // TODO: bogus value
            parts.add(MultipartPart.create(entry.getKey(), entry.getValue(), eTag, lastModified));
        }
    } else {
        parts = blobStore.listMultipartUpload(mpu);
    }

    String encodingType = request.getParameter("encoding-type");

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();
        xml.writeStartElement("ListPartsResult");
        xml.writeDefaultNamespace(AWS_XMLNS);

        if (encodingType != null && encodingType.equals("url")) {
            writeSimpleElement(xml, "EncodingType", encodingType);
        }

        writeSimpleElement(xml, "Bucket", containerName);
        writeSimpleElement(xml, "Key", encodeBlob(encodingType, blobName));
        writeSimpleElement(xml, "UploadId", uploadId);
        writeInitiatorStanza(xml);
        writeOwnerStanza(xml);
        writeSimpleElement(xml, "StorageClass", "STANDARD");

        // TODO: pagination
        /*
                    writeSimpleElement(xml, "PartNumberMarker", "1");
                    writeSimpleElement(xml, "NextPartNumberMarker", "3");
                    writeSimpleElement(xml, "MaxParts", "2");
                    writeSimpleElement(xml, "IsTruncated", "true");
        */

        for (MultipartPart part : parts) {
            xml.writeStartElement("Part");

            writeSimpleElement(xml, "PartNumber", String.valueOf(part.partNumber()));

            Date lastModified = part.lastModified();
            if (lastModified != null) {
                writeSimpleElement(xml, "LastModified", formatDate(lastModified));
            }

            String eTag = part.partETag();
            if (eTag != null) {
                writeSimpleElement(xml, "ETag", maybeQuoteETag(eTag));
            }

            writeSimpleElement(xml, "Size", String.valueOf(part.partSize()));

            xml.writeEndElement();
        }

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

From source file:org.openmrs.web.controller.encounter.EncounterFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest,
 *      java.lang.Object, org.springframework.validation.Errors)
 *//*  ww  w .  ja v  a2s  .  c o  m*/
@Override
protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors error)
        throws Exception {

    Encounter encounter = (Encounter) obj;

    // the generic returned key-value pair mapping
    Map<String, Object> map = new HashMap<String, Object>();

    // obsIds of obs that were edited
    List<Integer> editedObs = new Vector<Integer>();

    // the map returned to the form
    // This is a mapping between the formfield and a list of the Obs/ObsGroup in that field
    // This mapping is sorted according to the comparator in FormField.java
    SortedMap<FormField, List<Obs>> obsMapToReturn = null;
    String sortType = Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER);
    if ("weight".equals(sortType)) {
        obsMapToReturn = new TreeMap<FormField, List<Obs>>(); // use FormField.compareTo
    } else {
        obsMapToReturn = new TreeMap<FormField, List<Obs>>(new NumberingFormFieldComparator()); // use custom comparator
    }

    // this maps the obs to form field objects for non top-level obs
    // it is keyed on obs so that when looping over an exploded obsGroup
    // the formfield can be fetched easily (in order to show the field numbers etc)
    Map<Obs, FormField> otherFormFields = new HashMap<Obs, FormField>();

    if (Context.isAuthenticated()) {
        EncounterService es = Context.getEncounterService();
        FormService fs = Context.getFormService();

        // used to restrict the form field lookup
        Form form = encounter.getForm();

        List<EncounterType> encTypes = es.getAllEncounterTypes();
        // Non-retired types first
        Collections.sort(encTypes, new MetadataComparator(Context.getLocale()));
        map.put("encounterTypes", encTypes);

        map.put("encounterRoles", es.getAllEncounterRoles(false));
        map.put("forms", Context.getFormService().getAllForms());
        // loop over the encounter's observations to find the edited obs
        for (Obs o : encounter.getObsAtTopLevel(true)) {

            // only edited obs has previous version
            if (o.hasPreviousVersion()) {
                editedObs.add(o.getObsId());
            }

            // get the formfield for this obs
            FormField ff = fs.getFormField(form, o.getConcept(), obsMapToReturn.keySet(), false);
            if (ff == null) {
                ff = new FormField();
            }

            // we only put the top-level obs in the obsMap.  Those would
            // be the obs that don't have an obs grouper 
            if (o.getObsGroup() == null) {
                // populate the obs map with this formfield and obs
                List<Obs> list = obsMapToReturn.get(ff);
                if (list == null) {
                    list = new Vector<Obs>();
                    obsMapToReturn.put(ff, list);
                }
                list.add(o);
            } else {
                // this is not a top-level obs, just put the formField
                // in a separate list and be done with it
                otherFormFields.put(o, ff);
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("setting obsMap in page context (size: " + obsMapToReturn.size() + ")");
    }
    map.put("obsMap", obsMapToReturn);

    map.put("otherFormFields", otherFormFields);

    map.put("locale", Context.getLocale());
    map.put("editedObs", editedObs);
    if (encounter.getPatient() != null) {
        map.put("patientVisits", Context.getVisitService().getVisitsByPatient(encounter.getPatient()));
    }

    return map;
}

From source file:org.torproject.ernie.web.ExoneraTorServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    /* Start writing response. */
    PrintWriter out = response.getWriter();
    writeHeader(out);//  w  w w  . j  a  va  2 s  .co  m

    /* Look up first and last consensus in the database. */
    long firstValidAfter = -1L, lastValidAfter = -1L;
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT MIN(validafter) AS first, " + "MAX(validafter) AS last FROM consensus";
        ResultSet rs = statement.executeQuery(query);
        if (rs.next()) {
            firstValidAfter = rs.getTimestamp(1).getTime();
            lastValidAfter = rs.getTimestamp(2).getTime();
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        /* Looks like we don't have any consensuses. */
    }
    if (firstValidAfter < 0L || lastValidAfter < 0L) {
        out.println("<p><font color=\"red\"><b>Warning: </b></font>This "
                + "server doesn't have any relay lists available. If this " + "problem persists, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
        writeFooter(out);
        return;
    }

    out.println("<a name=\"relay\"></a><h3>Was there a Tor relay running " + "on this IP address?</h3>");

    /* Parse IP parameter. */
    Pattern ipAddressPattern = Pattern
            .compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
                    + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
    String ipParameter = request.getParameter("ip");
    String relayIP = "", ipWarning = "";
    if (ipParameter != null && ipParameter.length() > 0) {
        Matcher ipParameterMatcher = ipAddressPattern.matcher(ipParameter);
        if (ipParameterMatcher.matches()) {
            String[] ipParts = ipParameter.split("\\.");
            relayIP = Integer.parseInt(ipParts[0]) + "." + Integer.parseInt(ipParts[1]) + "."
                    + Integer.parseInt(ipParts[2]) + "." + Integer.parseInt(ipParts[3]);
        } else {
            ipWarning = "\""
                    + (ipParameter.length() > 20 ? ipParameter.substring(0, 20) + "[...]" : ipParameter)
                    + "\" is not a valid IP address.";
        }
    }

    /* Parse timestamp parameter. */
    String timestampParameter = request.getParameter("timestamp");
    long timestamp = 0L;
    String timestampStr = "", timestampWarning = "";
    SimpleDateFormat shortDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    shortDateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (timestampParameter != null && timestampParameter.length() > 0) {
        try {
            timestamp = shortDateTimeFormat.parse(timestampParameter).getTime();
            timestampStr = shortDateTimeFormat.format(timestamp);
            if (timestamp < firstValidAfter || timestamp > lastValidAfter) {
                timestampWarning = "Please pick a value between \""
                        + shortDateTimeFormat.format(firstValidAfter) + "\" and \""
                        + shortDateTimeFormat.format(lastValidAfter) + "\".";
            }
        } catch (ParseException e) {
            /* We have no way to handle this exception, other than leaving
               timestampStr at "". */
            timestampWarning = "\""
                    + (timestampParameter.length() > 20 ? timestampParameter.substring(0, 20) + "[...]"
                            : timestampParameter)
                    + "\" is not a valid timestamp.";
        }
    }

    /* If either IP address or timestamp is provided, the other one must
     * be provided, too. */
    if (relayIP.length() < 1 && timestampStr.length() > 0 && ipWarning.length() < 1) {
        ipWarning = "Please provide an IP address.";
    }
    if (relayIP.length() > 0 && timestampStr.length() < 1 && timestampWarning.length() < 1) {
        timestampWarning = "Please provide a timestamp.";
    }

    /* Parse target IP parameter. */
    String targetIP = "", targetPort = "", target = "";
    String[] targetIPParts = null;
    String targetAddrParameter = request.getParameter("targetaddr");
    String targetAddrWarning = "";
    if (targetAddrParameter != null && targetAddrParameter.length() > 0) {
        Matcher targetAddrParameterMatcher = ipAddressPattern.matcher(targetAddrParameter);
        if (targetAddrParameterMatcher.matches()) {
            String[] targetAddrParts = targetAddrParameter.split("\\.");
            targetIP = Integer.parseInt(targetAddrParts[0]) + "." + Integer.parseInt(targetAddrParts[1]) + "."
                    + Integer.parseInt(targetAddrParts[2]) + "." + Integer.parseInt(targetAddrParts[3]);
            target = targetIP;
            targetIPParts = targetIP.split("\\.");
        } else {
            targetAddrWarning = "\""
                    + (targetAddrParameter.length() > 20 ? timestampParameter.substring(0, 20) + "[...]"
                            : timestampParameter)
                    + "\" is not a valid IP address.";
        }
    }

    /* Parse target port parameter. */
    String targetPortParameter = request.getParameter("targetport");
    String targetPortWarning = "";
    if (targetPortParameter != null && targetPortParameter.length() > 0) {
        Pattern targetPortPattern = Pattern.compile("\\d+");
        if (targetPortParameter.length() < 5 && targetPortPattern.matcher(targetPortParameter).matches()
                && !targetPortParameter.equals("0") && Integer.parseInt(targetPortParameter) < 65536) {
            targetPort = targetPortParameter;
            if (target != null) {
                target += ":" + targetPort;
            } else {
                target = targetPort;
            }
        } else {
            targetPortWarning = "\""
                    + (targetPortParameter.length() > 8 ? targetPortParameter.substring(0, 8) + "[...]"
                            : targetPortParameter)
                    + "\" is not a valid TCP port.";
        }
    }

    /* If target port is provided, a target address must be provided,
     * too. */
    if (targetPort.length() > 0 && targetIP.length() < 1 && targetAddrWarning.length() < 1) {
        targetAddrWarning = "Please provide an IP address.";
    }

    /* Write form with IP address and timestamp. */
    out.println("        <form action=\"exonerator.html#relay\">\n"
            + "          <input type=\"hidden\" name=\"targetaddr\" "
            + (targetIP.length() > 0 ? " value=\"" + targetIP + "\"" : "") + ">\n"
            + "          <input type=\"hidden\" name=\"targetPort\""
            + (targetPort.length() > 0 ? " value=\"" + targetPort + "\"" : "") + ">\n" + "          <table>\n"
            + "            <tr>\n" + "              <td align=\"right\">IP address in question:" + "</td>\n"
            + "              <td><input type=\"text\" name=\"ip\""
            + (relayIP.length() > 0 ? " value=\"" + relayIP + "\"" : "") + ">"
            + (ipWarning.length() > 0 ? "<br><font color=\"red\">" + ipWarning + "</font>" : "") + "</td>\n"
            + "              <td><i>(Ex.: 1.2.3.4)</i></td>\n" + "            </tr>\n" + "            <tr>\n"
            + "              <td align=\"right\">Timestamp, in UTC:</td>\n"
            + "              <td><input type=\"text\" name=\"timestamp\""
            + (timestampStr.length() > 0 ? " value=\"" + timestampStr + "\"" : "") + ">"
            + (timestampWarning.length() > 0 ? "<br><font color=\"red\">" + timestampWarning + "</font>" : "")
            + "</td>\n" + "              <td><i>(Ex.: 2010-01-01 12:00)</i></td>\n" + "            </tr>\n"
            + "            <tr>\n" + "              <td></td>\n" + "              <td>\n"
            + "                <input type=\"submit\">\n" + "                <input type=\"reset\">\n"
            + "              </td>\n" + "              <td></td>\n" + "            </tr>\n"
            + "          </table>\n" + "        </form>\n");

    if (relayIP.length() < 1 || timestampStr.length() < 1) {
        writeFooter(out);
        return;
    }

    /* Look up relevant consensuses. */
    long timestampTooOld = timestamp - 15L * 60L * 60L * 1000L;
    long timestampFrom = timestamp - 3L * 60L * 60L * 1000L;
    long timestampTooNew = timestamp + 12L * 60L * 60L * 1000L;
    out.printf(
            "<p>Looking up IP address %s in the relay lists published " + "between %s and %s. "
                    + "Clients could have used any of these relay lists to "
                    + "select relays for their paths and build circuits using them. "
                    + "You may follow the links to relay lists and relay descriptors "
                    + "to grep for the lines printed below and confirm that results " + "are correct.<br>",
            relayIP, shortDateTimeFormat.format(timestampFrom), timestampStr);
    SimpleDateFormat validAfterTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    validAfterTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String fromValidAfter = validAfterTimeFormat.format(timestampTooOld);
    String toValidAfter = validAfterTimeFormat.format(timestampTooNew);
    SortedMap<Long, String> tooOldConsensuses = new TreeMap<Long, String>();
    SortedMap<Long, String> relevantConsensuses = new TreeMap<Long, String>();
    SortedMap<Long, String> tooNewConsensuses = new TreeMap<Long, String>();
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT validafter, rawdesc FROM consensus " + "WHERE validafter >= '" + fromValidAfter
                + "' AND validafter <= '" + toValidAfter + "'";
        ResultSet rs = statement.executeQuery(query);
        while (rs.next()) {
            long consensusTime = rs.getTimestamp(1).getTime();
            String rawConsensusString = new String(rs.getBytes(2), "US-ASCII");
            if (consensusTime < timestampFrom) {
                tooOldConsensuses.put(consensusTime, rawConsensusString);
            } else if (consensusTime > timestamp) {
                tooNewConsensuses.put(consensusTime, rawConsensusString);
            } else {
                relevantConsensuses.put(consensusTime, rawConsensusString);
            }
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        /* Looks like we don't have any consensuses in the requested
           interval. */
    }
    SortedMap<Long, String> allConsensuses = new TreeMap<Long, String>();
    allConsensuses.putAll(tooOldConsensuses);
    allConsensuses.putAll(relevantConsensuses);
    allConsensuses.putAll(tooNewConsensuses);
    if (allConsensuses.isEmpty()) {
        out.println("        <p>No relay lists found!</p>\n" + "        <p>Result is INDECISIVE!</p>\n"
                + "        <p>We cannot make any statement whether there was "
                + "a Tor relay running on IP address " + relayIP + " at " + timestampStr + "! We "
                + "did not find any relevant relay lists preceding the given "
                + "time. If you think this is an error on our side, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">contact " + "us</a>!</p>\n");
        writeFooter(out);
        return;
    }

    /* Parse consensuses to find descriptors belonging to the IP
       address. */
    SortedSet<Long> positiveConsensusesNoTarget = new TreeSet<Long>();
    Set<String> addressesInSameNetwork = new HashSet<String>();
    SortedMap<String, Set<Long>> relevantDescriptors = new TreeMap<String, Set<Long>>();
    SimpleDateFormat validAfterUrlFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    validAfterUrlFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    for (Map.Entry<Long, String> e : allConsensuses.entrySet()) {
        long consensus = e.getKey();
        if (relevantConsensuses.containsKey(consensus)) {
            long validAfterTime = -1L;
            String validAfterDatetime = validAfterTimeFormat.format(consensus);
            String validAfterString = validAfterUrlFormat.format(consensus);
            out.println("        <br><tt>valid-after <b>" + "<a href=\"consensus?valid-after="
                    + validAfterString + "\" target=\"_blank\">" + validAfterDatetime + "</b></a></tt><br>");
        }
        String rawConsensusString = e.getValue();
        BufferedReader br = new BufferedReader(new StringReader(rawConsensusString));
        String line = null;
        while ((line = br.readLine()) != null) {
            if (!line.startsWith("r ")) {
                continue;
            }
            String[] parts = line.split(" ");
            String address = parts[6];
            if (address.equals(relayIP)) {
                String hex = String.format("%040x", new BigInteger(1, Base64.decodeBase64(parts[3] + "==")));
                if (!relevantDescriptors.containsKey(hex)) {
                    relevantDescriptors.put(hex, new HashSet<Long>());
                }
                relevantDescriptors.get(hex).add(consensus);
                positiveConsensusesNoTarget.add(consensus);
                if (relevantConsensuses.containsKey(consensus)) {
                    out.println("    <tt>r " + parts[1] + " " + parts[2] + " " + "<a href=\"serverdesc?desc-id="
                            + hex + "\" " + "target=\"_blank\">" + parts[3] + "</a> " + parts[4] + " "
                            + parts[5] + " <b>" + parts[6] + "</b> " + parts[7] + " " + parts[8] + "</tt><br>");
                }
            } else {
                if (relayIP.startsWith(address.substring(0, address.lastIndexOf(".")))) {
                    addressesInSameNetwork.add(address);
                }
            }
        }
        br.close();
    }
    if (relevantDescriptors.isEmpty()) {
        out.printf(
                "        <p>None found!</p>\n" + "        <p>Result is NEGATIVE with moderate certainty!</p>\n"
                        + "        <p>We did not find IP " + "address " + relayIP
                        + " in any of the relay lists that were "
                        + "published between %s and %s.\n\nA possible "
                        + "reason for false negatives is that the relay is using a "
                        + "different IP address when generating a descriptor than for "
                        + "exiting to the Internet. We hope to provide better checks "
                        + "for this case in the future.</p>\n",
                shortDateTimeFormat.format(timestampTooOld), shortDateTimeFormat.format(timestampTooNew));
        if (!addressesInSameNetwork.isEmpty()) {
            out.println("        <p>The following other IP addresses of Tor "
                    + "relays were found in the mentioned relay lists that "
                    + "are in the same /24 network and that could be related to " + "IP address " + relayIP
                    + ":</p>\n");
            for (String s : addressesInSameNetwork) {
                out.println("        <p>" + s + "</p>\n");
            }
        }
        writeFooter(out);
        return;
    }

    /* Print out result. */
    Set<Long> matches = positiveConsensusesNoTarget;
    if (matches.contains(relevantConsensuses.lastKey())) {
        out.println("        <p>Result is POSITIVE with high certainty!" + "</p>\n"
                + "        <p>We found one or more relays on IP address " + relayIP
                + " in the most recent relay list preceding " + timestampStr
                + " that clients were likely to know.</p>\n");
    } else {
        boolean inOtherRelevantConsensus = false, inTooOldConsensuses = false, inTooNewConsensuses = false;
        for (long match : matches) {
            if (relevantConsensuses.containsKey(match)) {
                inOtherRelevantConsensus = true;
            } else if (tooOldConsensuses.containsKey(match)) {
                inTooOldConsensuses = true;
            } else if (tooNewConsensuses.containsKey(match)) {
                inTooNewConsensuses = true;
            }
        }
        if (inOtherRelevantConsensus) {
            out.println("        <p>Result is POSITIVE " + "with moderate certainty!</p>\n");
            out.println("<p>We found one or more relays on IP address " + relayIP
                    + ", but not in the relay list immediately " + "preceding " + timestampStr
                    + ". A possible reason for the "
                    + "relay being missing in the last relay list preceding the "
                    + "given time might be that some of the directory "
                    + "authorities had difficulties connecting to the relay. "
                    + "However, clients might still have used the relay.</p>\n");
        } else {
            out.println("        <p>Result is NEGATIVE " + "with high certainty!</p>\n");
            out.println("        <p>We did not find any relay on IP address " + relayIP
                    + " in the relay lists 3 hours preceding " + timestampStr + ".</p>\n");
            if (inTooOldConsensuses || inTooNewConsensuses) {
                if (inTooOldConsensuses && !inTooNewConsensuses) {
                    out.println("        <p>Note that we found a matching relay "
                            + "in relay lists that were published between 5 and 3 " + "hours before "
                            + timestampStr + ".</p>\n");
                } else if (!inTooOldConsensuses && inTooNewConsensuses) {
                    out.println("        <p>Note that we found a matching relay "
                            + "in relay lists that were published up to 2 hours " + "after " + timestampStr
                            + ".</p>\n");
                } else {
                    out.println("        <p>Note that we found a matching relay "
                            + "in relay lists that were published between 5 and 3 "
                            + "hours before and in relay lists that were published " + "up to 2 hours after "
                            + timestampStr + ".</p>\n");
                }
                out.println("<p>Make sure that the timestamp you provided is "
                        + "in the correct timezone: UTC (or GMT).</p>");
            }
            writeFooter(out);
            return;
        }
    }

    /* Second part: target */
    out.println("<br><a name=\"exit\"></a><h3>Was this relay configured "
            + "to permit exiting to a given target?</h3>");

    out.println("        <form action=\"exonerator.html#exit\">\n"
            + "              <input type=\"hidden\" name=\"timestamp\"\n" + "                         value=\""
            + timestampStr + "\">\n" + "              <input type=\"hidden\" name=\"ip\" " + "value=\""
            + relayIP + "\">\n" + "          <table>\n" + "            <tr>\n"
            + "              <td align=\"right\">Target address:</td>\n"
            + "              <td><input type=\"text\" name=\"targetaddr\""
            + (targetIP.length() > 0 ? " value=\"" + targetIP + "\"" : "") + "\">"
            + (targetAddrWarning.length() > 0 ? "<br><font color=\"red\">" + targetAddrWarning + "</font>" : "")
            + "</td>\n" + "              <td><i>(Ex.: 4.3.2.1)</i></td>\n" + "            </tr>\n"
            + "            <tr>\n" + "              <td align=\"right\">Target port:</td>\n"
            + "              <td><input type=\"text\" name=\"targetport\""
            + (targetPort.length() > 0 ? " value=\"" + targetPort + "\"" : "") + ">"
            + (targetPortWarning.length() > 0 ? "<br><font color=\"red\">" + targetPortWarning + "</font>" : "")
            + "</td>\n" + "              <td><i>(Ex.: 80)</i></td>\n" + "            </tr>\n"
            + "            <tr>\n" + "              <td></td>\n" + "              <td>\n"
            + "                <input type=\"submit\">\n" + "                <input type=\"reset\">\n"
            + "              </td>\n" + "              <td></td>\n" + "            </tr>\n"
            + "          </table>\n" + "        </form>\n");

    if (targetIP.length() < 1) {
        writeFooter(out);
        return;
    }

    /* Parse router descriptors to check exit policies. */
    out.println("<p>Searching the relay descriptors published by the " + "relay on IP address " + relayIP
            + " to find out whether this " + "relay permitted exiting to " + target + ". You may follow the "
            + "links above to the relay descriptors and grep them for the "
            + "lines printed below to confirm that results are correct.</p>");
    SortedSet<Long> positiveConsensuses = new TreeSet<Long>();
    Set<String> missingDescriptors = new HashSet<String>();
    Set<String> descriptors = relevantDescriptors.keySet();
    for (String descriptor : descriptors) {
        byte[] rawDescriptor = null;
        try {
            Connection conn = this.ds.getConnection();
            Statement statement = conn.createStatement();
            String query = "SELECT rawdesc FROM descriptor " + "WHERE descriptor = '" + descriptor + "'";
            ResultSet rs = statement.executeQuery(query);
            if (rs.next()) {
                rawDescriptor = rs.getBytes(1);
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            /* Consider this descriptors as 'missing'. */
            continue;
        }
        if (rawDescriptor != null && rawDescriptor.length > 0) {
            missingDescriptors.remove(descriptor);
            String rawDescriptorString = new String(rawDescriptor, "US-ASCII");
            try {
                BufferedReader br = new BufferedReader(new StringReader(rawDescriptorString));
                String line = null, routerLine = null, publishedLine = null;
                StringBuilder acceptRejectLines = new StringBuilder();
                boolean foundMatch = false;
                while ((line = br.readLine()) != null) {
                    if (line.startsWith("router ")) {
                        routerLine = line;
                    } else if (line.startsWith("published ")) {
                        publishedLine = line;
                    } else if (line.startsWith("reject ") || line.startsWith("accept ")) {
                        if (foundMatch) {
                            out.println("<tt> " + line + "</tt><br>");
                            continue;
                        }
                        boolean ruleAccept = line.split(" ")[0].equals("accept");
                        String ruleAddress = line.split(" ")[1].split(":")[0];
                        if (!ruleAddress.equals("*")) {
                            if (!ruleAddress.contains("/") && !ruleAddress.equals(targetIP)) {
                                /* IP address does not match. */
                                acceptRejectLines.append("<tt> " + line + "</tt><br>\n");
                                continue;
                            }
                            String[] ruleIPParts = ruleAddress.split("/")[0].split("\\.");
                            int ruleNetwork = ruleAddress.contains("/")
                                    ? Integer.parseInt(ruleAddress.split("/")[1])
                                    : 32;
                            for (int i = 0; i < 4; i++) {
                                if (ruleNetwork == 0) {
                                    break;
                                } else if (ruleNetwork >= 8) {
                                    if (ruleIPParts[i].equals(targetIPParts[i])) {
                                        ruleNetwork -= 8;
                                    } else {
                                        break;
                                    }
                                } else {
                                    int mask = 255 ^ 255 >>> ruleNetwork;
                                    if ((Integer.parseInt(ruleIPParts[i])
                                            & mask) == (Integer.parseInt(targetIPParts[i]) & mask)) {
                                        ruleNetwork = 0;
                                    }
                                    break;
                                }
                            }
                            if (ruleNetwork > 0) {
                                /* IP address does not match. */
                                acceptRejectLines.append("<tt> " + line + "</tt><br>\n");
                                continue;
                            }
                        }
                        String rulePort = line.split(" ")[1].split(":")[1];
                        if (targetPort.length() < 1 && !ruleAccept && !rulePort.equals("*")) {
                            /* With no port given, we only consider reject :* rules as
                               matching. */
                            acceptRejectLines.append("<tt> " + line + "</tt><br>\n");
                            continue;
                        }
                        if (targetPort.length() > 0 && !rulePort.equals("*") && rulePort.contains("-")) {
                            int fromPort = Integer.parseInt(rulePort.split("-")[0]);
                            int toPort = Integer.parseInt(rulePort.split("-")[1]);
                            int targetPortInt = Integer.parseInt(targetPort);
                            if (targetPortInt < fromPort || targetPortInt > toPort) {
                                /* Port not contained in interval. */
                                continue;
                            }
                        }
                        if (targetPort.length() > 0) {
                            if (!rulePort.equals("*") && !rulePort.contains("-")
                                    && !targetPort.equals(rulePort)) {
                                /* Ports do not match. */
                                acceptRejectLines.append("<tt> " + line + "</tt><br>\n");
                                continue;
                            }
                        }
                        boolean relevantMatch = false;
                        for (long match : relevantDescriptors.get(descriptor)) {
                            if (relevantConsensuses.containsKey(match)) {
                                relevantMatch = true;
                            }
                        }
                        if (relevantMatch) {
                            String[] routerParts = routerLine.split(" ");
                            out.println("<br><tt>" + routerParts[0] + " " + routerParts[1] + " <b>"
                                    + routerParts[2] + "</b> " + routerParts[3] + " " + routerParts[4] + " "
                                    + routerParts[5] + "</tt><br>");
                            String[] publishedParts = publishedLine.split(" ");
                            out.println("<tt>" + publishedParts[0] + " <b>" + publishedParts[1] + " "
                                    + publishedParts[2] + "</b></tt><br>");
                            out.println(acceptRejectLines.toString());
                            out.println("<tt><b>" + line + "</b></tt><br>");
                            foundMatch = true;
                        }
                        if (ruleAccept) {
                            positiveConsensuses.addAll(relevantDescriptors.get(descriptor));
                        }
                    }
                }
                br.close();
            } catch (IOException e) {
                /* Could not read descriptor string. */
                continue;
            }
        }
    }

    /* Print out result. */
    matches = positiveConsensuses;
    if (matches.contains(relevantConsensuses.lastKey())) {
        out.println("        <p>Result is POSITIVE with high certainty!</p>" + "\n"
                + "        <p>We found one or more relays on IP address " + relayIP + " permitting exit to "
                + target + " in the most recent relay list preceding " + timestampStr
                + " that clients were likely to know.</p>\n");
        writeFooter(out);
        return;
    }
    boolean resultIndecisive = target.length() > 0 && !missingDescriptors.isEmpty();
    if (resultIndecisive) {
        out.println("        <p>Result is INDECISIVE!</p>\n"
                + "        <p>At least one referenced descriptor could not be "
                + "found. This is a rare case, but one that (apparently) "
                + "happens. We cannot make any good statement about exit "
                + "relays without these descriptors. The following descriptors " + "are missing:</p>");
        for (String desc : missingDescriptors)
            out.println("        <p>" + desc + "</p>\n");
    }
    boolean inOtherRelevantConsensus = false, inTooOldConsensuses = false, inTooNewConsensuses = false;
    for (long match : matches) {
        if (relevantConsensuses.containsKey(match)) {
            inOtherRelevantConsensus = true;
        } else if (tooOldConsensuses.containsKey(match)) {
            inTooOldConsensuses = true;
        } else if (tooNewConsensuses.containsKey(match)) {
            inTooNewConsensuses = true;
        }
    }
    if (inOtherRelevantConsensus) {
        if (!resultIndecisive) {
            out.println("        <p>Result is POSITIVE " + "with moderate certainty!</p>\n");
        }
        out.println("<p>We found one or more relays on IP address " + relayIP + " permitting exit to " + target
                + ", but not in " + "the relay list immediately preceding " + timestampStr
                + ". A possible reason for the relay being missing in the last "
                + "relay list preceding the given time might be that some of "
                + "the directory authorities had difficulties connecting to "
                + "the relay. However, clients might still have used the " + "relay.</p>\n");
    } else {
        if (!resultIndecisive) {
            out.println("        <p>Result is NEGATIVE " + "with high certainty!</p>\n");
        }
        out.println("        <p>We did not find any relay on IP address " + relayIP + " permitting exit to "
                + target + " in the relay list 3 hours preceding " + timestampStr + ".</p>\n");
        if (inTooOldConsensuses || inTooNewConsensuses) {
            if (inTooOldConsensuses && !inTooNewConsensuses) {
                out.println("        <p>Note that we found a matching relay in "
                        + "relay lists that were published between 5 and 3 " + "hours before " + timestampStr
                        + ".</p>\n");
            } else if (!inTooOldConsensuses && inTooNewConsensuses) {
                out.println("        <p>Note that we found a matching relay in "
                        + "relay lists that were published up to 2 hours after " + timestampStr + ".</p>\n");
            } else {
                out.println("        <p>Note that we found a matching relay in "
                        + "relay lists that were published between 5 and 3 "
                        + "hours before and in relay lists that were published up " + "to 2 hours after "
                        + timestampStr + ".</p>\n");
            }
            out.println("<p>Make sure that the timestamp you provided is "
                    + "in the correct timezone: UTC (or GMT).</p>");
        }
    }
    if (target != null) {
        if (positiveConsensuses.isEmpty() && !positiveConsensusesNoTarget.isEmpty()) {
            out.println("        <p>Note that although the found relay(s) did " + "not permit exiting to "
                    + target + ", there have been one " + "or more relays running at the given time.</p>");
        }
    }

    /* Finish writing response. */
    writeFooter(out);
}

From source file:com.aurel.track.exchange.excel.ExcelImportBL.java

/**
 * Add a new conflict for a field from a row
 * /*from   www.  j a  v  a2s .c o m*/
 * @param conflictsMap
 * @param row
 * @param fieldID
 * @param workItemBean
 * @param workItemBeanOriginal
 * @param locale
 */
private static void addAsConfict(SortedMap<Integer, SortedMap<Integer, Map<Integer, Object>>> conflictsMap,
        Integer row, Integer fieldID, TWorkItemBean workItemBean, TWorkItemBean workItemBeanOriginal,
        Map<Integer, String> columnIndexToColumNameMap, Map<Integer, Integer> fieldIDToColumnIndexMap,
        Map<String, Boolean> overwriteMap, Map<Integer, Boolean> fieldForWorkItemOverwrite, Locale locale) {

    Boolean overwrite = null;
    if (fieldForWorkItemOverwrite != null) {
        // overwrite flag submitted from the user
        overwrite = fieldForWorkItemOverwrite.get(fieldID);
    }
    if (overwrite != null) {
        // was already submitted
        if (!overwrite.booleanValue()) {
            // user decided to leave the track+ value change back to
            // original: reset the changes made from excel
            workItemBean.setAttribute(fieldID, workItemBeanOriginal.getAttribute(fieldID));
        }
        // do not render conflict again once the user submitted his conflict
        // resolution choice
        return;
    }

    SortedMap<Integer, Map<Integer, Object>> fieldConflictsForRow = conflictsMap.get(row);
    if (fieldConflictsForRow == null) {
        fieldConflictsForRow = new TreeMap<Integer, Map<Integer, Object>>();
        conflictsMap.put(row, fieldConflictsForRow);
    }
    // add map for field
    Map<Integer, Object> fieldConflictMap = new HashMap<Integer, Object>();
    fieldConflictsForRow.put(fieldID, fieldConflictMap);
    IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
    String excelShowValue = fieldTypeRT.getShowValue(workItemBean.getAttribute(fieldID), locale);
    String trackPlusShowValue = fieldTypeRT.getShowValue(workItemBeanOriginal.getAttribute(fieldID), locale);
    fieldConflictMap.put(IConflictMapEntry.WORKITEMID, workItemBean.getObjectID());
    Integer columnIndex = fieldIDToColumnIndexMap.get(fieldID);
    if (columnIndex != null) {
        // column is mapped
        fieldConflictMap.put(IConflictMapEntry.COLUMN_LETTER,
                ExcelFieldMatchBL.colNumericToLetter(columnIndex));
        fieldConflictMap.put(IConflictMapEntry.FELED_NAME, columnIndexToColumNameMap.get(columnIndex));
    } else {
        // (probably mandatory) column not mapped, take the track+ field
        // label
        fieldConflictMap.put(IConflictMapEntry.FELED_NAME,
                FieldRuntimeBL.getLocalizedDefaultFieldLabel(fieldID, locale));
    }
    fieldConflictMap.put(IConflictMapEntry.EXCEL_VALUE, excelShowValue);
    fieldConflictMap.put(IConflictMapEntry.TRACKPLUS_VALUE, trackPlusShowValue);
    String combinedField = workItemBean.getObjectID() + SPLITTER + fieldID;
    fieldConflictMap.put(IConflictMapEntry.WORKITEMID_FIELDID, combinedField);
    overwriteMap.put(combinedField, IConflictResolution.OVERWRITE);
}

From source file:org.gvnix.web.screen.roo.addon.AbstractPatternMetadata.java

public AbstractPatternMetadata(String mid, JavaType aspect, PhysicalTypeMetadata controllerMetadata,
        MemberDetails controllerDetails, WebScaffoldMetadata webScaffoldMetadata,
        List<StringAttributeValue> patterns, PhysicalTypeMetadata entityMetadata,
        SortedMap<JavaType, JavaTypeMetadataDetails> relatedEntities,
        SortedMap<JavaType, JavaTypeMetadataDetails> relatedFields,
        Map<JavaType, Map<JavaSymbolName, DateTimeFormatDetails>> relatedDates,
        Map<JavaSymbolName, DateTimeFormatDetails> entityDateTypes) {

    super(mid, aspect, controllerMetadata);

    // Required parameters: Web scaffold information and relatedEntities
    // details (entity and optional master entity)
    Validate.notNull(webScaffoldMetadata, "Web scaffold metadata required");
    Validate.notNull(relatedEntities, "Related relatedEntities type metadata details required");

    if (!isValid()) {

        // This metadata instance not be already produced at the time of
        // instantiation (will retry)
        return;/*from w  w  w .  ja va 2s.com*/
    }

    this.webScaffoldMetadata = webScaffoldMetadata;
    this.entity = entityMetadata.getMemberHoldingTypeDetails().getName();
    this.relatedEntities = relatedEntities;
    this.entityTypeDetails = relatedEntities.get(entity);
    this.entityDateTypes = entityDateTypes;

    this.controllerMethods = controllerDetails.getMethods();
    this.controllerFields = controllerDetails.getFields();

    Validate.notNull(entityTypeDetails, "Metadata holder required for form backing type: " + entity);
    Validate.notNull(entityTypeDetails.getPersistenceDetails(),
            "PersistenceMetadata details required for form backing type: " + entity);

    WebScaffoldAnnotationValues webScaffoldValues = new WebScaffoldAnnotationValues(controllerMetadata);
    if (webScaffoldValues.isPopulateMethods()) {

        filterAlreadyPopulatedTypes(relatedFields);
    }

    this.relatedFields = relatedFields;
    this.relatedDates = relatedDates;

    // TODO: Take care of attributes "create, update, delete" in
    // RooWebScaffold annotation
    List<String> definedPatternsList = new ArrayList<String>();
    for (StringAttributeValue definedPattern : patterns) {

        definedPatternsList.add(definedPattern.getValue());
    }

    this.aspectPackage = aspect.getPackage().getFullyQualifiedPackageName();

    this.patterns = Collections.unmodifiableList(definedPatternsList);

    builder.addField(getDefinedPatternField());

    List<String> tabularPatterns = getPatternTypeDefined(WebPatternType.tabular, this.patterns);
    if (!tabularPatterns.isEmpty()) {

        // TODO findAll method required on this pattern ?
        if (entityTypeDetails.getPersistenceDetails().getFindAllMethod() == null) {

            // TODO: If no find all method, all other patterns are not
            // generated ?
            return;
        }

        for (String tabularPattern : tabularPatterns) {

            builder.addMethod(getTabularMethod(tabularPattern));
        }

        builder.addMethod(getCreateListMethod());
        builder.addMethod(getUpdateListMethod());
        builder.addMethod(getDeleteListMethod());
        builder.addMethod(getFilterListMethod());
        builder.addMethod(getRefererRedirectMethod());
        builder.addMethod(getFilterBindingErrorsMethod());
    }

    List<String> registerPatterns = getPatternTypeDefined(WebPatternType.register, this.patterns);
    if (!registerPatterns.isEmpty()) {

        // TODO findEntries method required on this pattern ?
        if (entityTypeDetails.getPersistenceDetails().getFindEntriesMethod() == null) {

            // TODO: If no find entries method, all other patterns are not
            // generated ?
            return;
        }

        for (String registerPattern : registerPatterns) {

            builder.addMethod(getRegisterMethod(registerPattern));
            builder.addMethod(getDeleteMethod(registerPattern));
        }

        builder.addMethod(getRefererQueryMethod());
    }

    List<String> tabularEditPatterns = getPatternTypeDefined(WebPatternType.tabular_edit_register,
            this.patterns);
    if (!tabularEditPatterns.isEmpty()) {

        // TODO findAll method required on this pattern ?
        if (entityTypeDetails.getPersistenceDetails().getFindAllMethod() == null) {

            // TODO: If no find all method, all other patterns are not
            // generated ?
            return;
        }

        for (String tabularEditPattern : tabularEditPatterns) {

            builder.addMethod(getTabularMethod(tabularEditPattern));
        }

        builder.addMethod(getDeleteListMethod());
        builder.addMethod(getFilterListMethod());
        builder.addMethod(getRefererRedirectMethod());
        builder.addMethod(getRefererQueryMethod());
        builder.addMethod(getFilterBindingErrorsMethod());
    }
}