Example usage for java.util SortedSet first

List of usage examples for java.util SortedSet first

Introduction

In this page you can find the example usage for java.util SortedSet first.

Prototype

E first();

Source Link

Document

Returns the first (lowest) element currently in this set.

Usage

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

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

    /* Measure how long it takes to process this request. */
    long started = System.currentTimeMillis();

    /* Get print writer and start writing response. */
    PrintWriter out = response.getWriter();
    writeHeader(out);/* w  w w  .  j a  v  a2s  . c om*/

    /* Check fingerprint parameter. */
    String fingerprintParameter = request.getParameter("fingerprint");
    boolean validParameter = true;
    if (fingerprintParameter == null || fingerprintParameter.length() < 8
            || fingerprintParameter.length() > 40) {
        validParameter = false;
    } else {
        Pattern fingerprintPattern = Pattern.compile("^[0-9a-f]{8,40}$");
        if (!fingerprintPattern.matcher(fingerprintParameter.toLowerCase()).matches()) {
            validParameter = false;
        }
    }
    if (!validParameter) {
        out.write("    <br/><p>Sorry, \"" + fingerprintParameter
                + "\" is not a valid relay fingerprint. Please provide at "
                + "least the first 8 hex characters of a relay " + "fingerprint.</p>\n");
        writeFooter(out);
        return;
    }

    /* If we were only given a partial fingerprint, look up all
     * fingerprints starting with that part to see if it's unique in the
     * last 30 days. */
    String fingerprint = fingerprintParameter.toLowerCase();
    if (fingerprint.length() < 40) {
        SortedSet<String> allFingerprints = new TreeSet<String>();
        try {
            Connection conn = this.ds.getConnection();
            Statement statement = conn.createStatement();
            String query = "SELECT DISTINCT fingerprint FROM statusentry " + "WHERE validafter >= '"
                    + this.dayFormat.format(started - 30L * 24L * 60L * 60L * 1000L)
                    + " 00:00:00' AND fingerprint LIKE '" + fingerprint + "%'";
            ResultSet rs = statement.executeQuery(query);
            while (rs.next()) {
                allFingerprints.add(rs.getString(1));
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            out.println("<p><font color=\"red\"><b>Warning: </b></font>We "
                    + "experienced an unknown database problem while looking up "
                    + "the relay with fingerprint starting with " + fingerprintParameter
                    + ". If this problem persists, please "
                    + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
            writeFooter(out);
            return;
        }
        if (allFingerprints.size() == 0) {
            out.write("<p>No relay found with fingerprint starting with " + fingerprintParameter
                    + " in the last 30 days.</p>");
            writeFooter(out);
            return;
        } else if (allFingerprints.size() > 1) {
            out.println("<p>The fingerprint part " + fingerprintParameter
                    + " is not unique for relays running in the last 30 days. "
                    + "Please choose one of the following fingerprints:</p><ul>");
            for (String f : allFingerprints) {
                out.println("<li><a href=\"relay.html?fingerprint=" + f + "\">" + f + "</a></li>");
            }
            out.write("</ul><br/>");
            writeFooter(out);
            return;
        } else {
            fingerprint = allFingerprints.first();
        }
    }

    /* Print out in which consensuses this relay was last contained. */
    boolean foundRelay = false;
    String lastDescriptor = null;
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT validafter, rawdesc FROM statusentry WHERE " + "validafter >= '"
                + this.dayFormat.format(started - 30L * 24L * 60L * 60L * 1000L)
                + " 00:00:00' AND fingerprint = '" + fingerprint + "' ORDER BY validafter DESC LIMIT 3";
        ResultSet rs = statement.executeQuery(query);
        boolean printedDescription = false;
        while (rs.next()) {
            foundRelay = true;
            if (!printedDescription) {
                out.println("<p>The relay with fingerprint "
                        + (fingerprintParameter.length() < 40 ? "starting " : "") + "with "
                        + fingerprintParameter + " was last " + "referenced in the following relay lists:</p>");
                printedDescription = true;
            }
            String validAfter = rs.getTimestamp(1).toString().substring(0, 19);
            out.println("        <br/><tt>valid-after " + "<a href=\"consensus?valid-after="
                    + validAfter.replaceAll(":", "-").replaceAll(" ", "-") + "\" target=\"_blank\">"
                    + validAfter + "</a></tt><br/>");
            byte[] rawStatusEntry = rs.getBytes(2);
            try {
                String statusEntryLines = new String(rawStatusEntry, "US-ASCII");
                String[] lines = statusEntryLines.split("\n");
                for (String line : lines) {
                    if (line.startsWith("r ")) {
                        String[] parts = line.split(" ");
                        String descriptor = String.format("%040x",
                                new BigInteger(1, Base64.decodeBase64(parts[3] + "==")));
                        if (lastDescriptor == null) {
                            lastDescriptor = descriptor;
                        }
                        out.println("    <tt>r " + parts[1] + " " + parts[2] + " "
                                + "<a href=\"descriptor.html?desc-id=" + descriptor + "\" target=\"_blank\">"
                                + parts[3] + "</a> " + parts[4] + " " + parts[5] + " " + parts[6] + " "
                                + parts[7] + " " + parts[8] + "</tt><br/>");
                    } else {
                        out.println("    <tt>" + line + "</tt><br/>");
                    }
                }
            } catch (UnsupportedEncodingException e) {
                /* This shouldn't happen, because we know that ASCII is
                 * supported. */
            }
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        out.println("<p><font color=\"red\"><b>Warning: </b></font>We "
                + "experienced an unknown database problem while looking up " + "the relay with fingerprint "
                + (fingerprintParameter.length() < 40 ? "starting with " : "") + fingerprintParameter
                + ". If this problem persists, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
        writeFooter(out);
        return;
    }

    /* If we didn't find this relay, stop here. */
    if (!foundRelay) {
        out.write("<p>No relay found with fingerprint "
                + (fingerprintParameter.length() < 40 ? "starting with " : "") + fingerprintParameter
                + " in the last 30 days.</p>");
        writeFooter(out);
        return;
    }

    /* Look up last server and extra-info descriptor in the database. */
    String query = null, descriptor = null, nickname = null, published = null, extrainfo = null;
    byte[] rawDescriptor = null, rawExtrainfo = null;
    if (lastDescriptor != null) {
        try {
            Connection conn = this.ds.getConnection();
            Statement statement = conn.createStatement();
            query = "SELECT descriptor, nickname, published, extrainfo, "
                    + "rawdesc FROM descriptor WHERE descriptor = '" + lastDescriptor + "'";
            ResultSet rs = statement.executeQuery(query);
            if (rs.next()) {
                descriptor = rs.getString(1);
                nickname = rs.getString(2);
                published = rs.getTimestamp(3).toString().substring(0, 19);
                extrainfo = rs.getString(4);
                rawDescriptor = rs.getBytes(5);
                query = "SELECT rawdesc FROM extrainfo WHERE extrainfo = '" + extrainfo + "'";
                rs = statement.executeQuery(query);
                if (rs.next()) {
                    rawExtrainfo = rs.getBytes(1);
                }
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            out.write("<br/><p><font color=\"red\"><b>Warning: </b></font>"
                    + "Internal server error when looking up descriptor. The " + "query was '" + query
                    + "'. If this problem persists, " + "please "
                    + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
            writeFooter(out);
            return;
        }
    }

    /* If no descriptor was found, stop here. */
    if (descriptor == null) {
        out.write("<p>No descriptor found with identifier " + descriptor
                + " which was referenced in the last relay list.</p>");
        writeFooter(out);
        return;
    }

    /* Print out both server and extra-info descriptor. */
    out.write("<br/><p>The last referenced server descriptor published " + "by this relay is:</p>");
    BufferedReader br = new BufferedReader(new StringReader(new String(rawDescriptor, "US-ASCII")));
    String line = null;
    while ((line = br.readLine()) != null) {
        out.println("        <tt>" + line + "</tt><br/>");
    }
    br.close();
    if (rawExtrainfo != null) {
        out.println("<br/><p>Together with this server descriptor, the "
                + "relay published the following extra-info descriptor:</p>");
        br = new BufferedReader(new StringReader(new String(rawExtrainfo, "US-ASCII")));
        line = null;
        while ((line = br.readLine()) != null) {
            out.println("        <tt>" + line + "</tt><br/>");
        }
    }

    /* Provide links to raw descriptors, too. */
    out.println("<br/><p>Note that the descriptor" + (rawExtrainfo != null ? "s have" : " has")
            + " been converted to ASCII and reformatted "
            + "for display purposes. You may also download the raw " + "<a href=\"serverdesc?desc-id="
            + descriptor + "\" target=\"_blank\">server " + "descriptor</a>"
            + (extrainfo != null
                    ? " and <a href=\"extrainfodesc?desc-id=" + extrainfo
                            + "\" target=\"_blank\">extra-info descriptor</a>"
                    : "")
            + " as " + (extrainfo != null ? "they were" : "it was")
            + " published to the directory authorities.</p>");

    /* Display total lookup time on the results page. */
    long searchTime = System.currentTimeMillis() - started;
    out.write("        <br/><p>Looking up this relay took us "
            + String.format("%d.%03d", searchTime / 1000, searchTime % 1000) + " seconds.</p>\n");

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

From source file:org.dllearner.reasoning.SPARQLReasoner.java

private OWLClassExpression computeDomain(OWLProperty property) {
    String query = String.format("SELECT ?domain WHERE {" + "<%s> <%s> ?domain. FILTER(isIRI(?domain))" + "}",
            property.toStringID(), RDFS.domain.getURI());

    try (QueryExecution qe = qef.createQueryExecution(query)) {
        ResultSet rs = qe.execSelect();
        SortedSet<OWLClassExpression> domains = new TreeSet<>();
        while (rs.hasNext()) {
            QuerySolution qs = rs.next();
            domains.add(df.getOWLClass(IRI.create(qs.getResource("domain").getURI())));
        }//  w w w .  j a va2 s  .c o  m
        domains.remove(df.getOWLThing());
        if (domains.size() == 1) {
            return domains.first();
        } else if (domains.size() > 1) {
            return df.getOWLObjectIntersectionOf(domains);
        }
        return df.getOWLThing();
    } catch (Exception e) {
        logger.error("Failed to compute the domain for " + property + ".", e);
    }
    return null;
}

From source file:org.dllearner.reasoning.SPARQLReasoner.java

@Override
public OWLClassExpression getRangeImpl(OWLObjectProperty property) {
    return objectPropertyRanges.computeIfAbsent(property, k -> {
        String query = String.format("SELECT ?range WHERE {" + "<%s> <%s> ?range. FILTER(isIRI(?range))" + "}",
                property.toStringID(), RDFS.range.getURI());

        try (QueryExecution qe = qef.createQueryExecution(query)) {
            ResultSet rs = qe.execSelect();
            SortedSet<OWLClassExpression> ranges = new TreeSet<>();
            while (rs.hasNext()) {
                QuerySolution qs = rs.next();
                ranges.add(df.getOWLClass(IRI.create(qs.getResource("range").getURI())));
            }//from   www  .  j  av a2s . com
            ranges.remove(df.getOWLThing());
            if (ranges.size() == 1) {
                return ranges.first();
            } else if (ranges.size() > 1) {
                return df.getOWLObjectIntersectionOf(ranges);
            }
            return df.getOWLThing();
        } catch (Exception e) {
            logger.error("Failed to compute range for " + property, e);
        }
        return null;
    });
}

From source file:net.sf.jasperreports.engine.export.HtmlExporter.java

protected void exportTable(TableVisitor tableVisitor, Table table, boolean whiteBackground,
        boolean isMainReportTable) throws IOException {
    SortedSet<Column> columns = table.getColumns().getUserEntries();
    SortedSet<Row> rows = table.getRows().getUserEntries();
    if (columns.isEmpty() || rows.isEmpty()) {
        // TODO lucianc empty page
        return;/* w w  w  . j a  v a  2 s .co  m*/
    }

    if (isMainReportTable) {
        int totalWidth = columns.last().getEndCoord() - columns.first().getStartCoord();
        writer.write(
                "<table class=\"jrPage\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"empty-cells: show; width: ");
        writer.write(toSizeUnit(totalWidth));
        writer.write(";");
    } else {
        writer.write(
                "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"empty-cells: show; width: 100%;");
    }

    HtmlBorderCollapseEnum borderCollapse = getCurrentItemConfiguration().getBorderCollapseValue();
    if (borderCollapse != null) {
        writer.write(" border-collapse: ");
        writer.write(borderCollapse.getName());
        writer.write(";");
    }

    if (whiteBackground) {
        writer.write(" background-color: white;");
    }
    writer.write("\">\n");

    // TODO lucianc check whether we can use the first row for setting col widths
    writer.write("<tr valign=\"top\" style=\"height:0\">\n");
    for (Column col : columns) {
        writer.write("<td style=\"width:");
        writer.write(toSizeUnit(col.getExtent()));
        writer.write("\"></td>\n");
    }
    writer.write("</tr>\n");

    for (Row row : rows) {
        writer.write("<tr valign=\"top\" style=\"height:");
        writer.write(toSizeUnit(row.getExtent()));
        writer.write("\">\n");

        int emptySpan = 0;
        for (Column col : columns) {
            Cell cell = row.getCell(col);
            if (cell == null) {
                ++emptySpan;
            } else {
                if (emptySpan > 0) {
                    writeEmptyCell(emptySpan, 1);
                }
                emptySpan = 0;

                TablePosition position = new TablePosition(table, col, row);
                cell.accept(tableVisitor, position);
            }
        }
        if (emptySpan > 0) {
            writeEmptyCell(emptySpan, 1);
        }

        writer.write("</tr>\n");
    }

    writer.write("</table>\n");
}

From source file:org.alfresco.repo.site.SiteServiceImpl.java

/**
 * @see org.alfresco.service.cmr.site.SiteService#getMembersRole(java.lang.String,
 *      java.lang.String)/*w  w  w.j  a  va  2 s  .  c om*/
 */
public String getMembersRole(String shortName, String authorityName) {
    String result = null;
    List<String> roles = getMembersRoles(shortName, authorityName);
    if (roles.size() != 0) {
        if (roles.size() > 1 && roleComparator != null) {
            // Need to sort the roles into the most important first.
            SortedSet<String> sortedRoles = new TreeSet<String>(roleComparator);
            for (String role : roles) {
                sortedRoles.add(role);
            }
            result = sortedRoles.first();
        } else {
            // don't search on precedence or only one result
            result = roles.get(0);
        }
    }
    return result;
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

private void createSchedule(SortedSet<DateTime> availableDates, Product product, Date version,
        SqlSession sqlSession) {/* w w w . ja  v  a 2s.c o  m*/
    DateTime currentDate = new DateTime(version).withTime(0, 0, 0, 0);

    // create reservation if current date is less than the first date in the available dates set
    DateTime firstAvailableDate = availableDates.first();
    int daysBetween = Days.daysBetween(currentDate, availableDates.first()).getDays();
    if (daysBetween > 1) {
        PartnerService.createSchedule(sqlSession, product, currentDate.toDate(),
                firstAvailableDate.withFieldAdded(DurationFieldType.days(), -1).toDate(), version);
    }

    DateTime fromDate = firstAvailableDate;

    boolean first = true;
    for (DateTime toDate : availableDates) {
        if (first) {
            first = false;
            continue;
        }
        daysBetween = Days.daysBetween(fromDate, toDate).getDays();
        if (daysBetween > 1 && toDate.isAfterNow()) {
            PartnerService.createSchedule(sqlSession, product,
                    fromDate.withFieldAdded(DurationFieldType.days(), 1).toDate(),
                    toDate.withFieldAdded(DurationFieldType.days(), -1).toDate(), version);
        }
        fromDate = toDate;
    }
}

From source file:net.cbtltd.rest.yandex.A_Handler.java

private void createSchedule(SortedSet<DateTime> availableDates, Product product, Date version,
        SqlSession sqlSession) {//w w w.  j  a v  a 2 s  . c  o m
    DateTime currentDate = new DateTime(version).withTime(0, 0, 0, 0);

    // create reservation if current date is less than the first date in the available dates set
    DateTime firstAvailableDate = availableDates.first();
    System.out.println("firstAvailableDate = " + firstAvailableDate);
    int daysBetween = Days.daysBetween(currentDate, availableDates.first()).getDays();
    System.out.println("createSchedule daysBetween: " + daysBetween);
    System.out.println("daysBetween = " + currentDate + ",  " + availableDates.first());
    if (daysBetween > 1) {
        PartnerService.createSchedule(sqlSession, product, currentDate.toDate(),
                firstAvailableDate.withFieldAdded(DurationFieldType.days(), -1).toDate(), version);
    }

    DateTime fromDate = firstAvailableDate;

    boolean first = true;
    System.out.println("availableDates size = " + availableDates.size());
    for (DateTime toDate : availableDates) {
        if (first) {
            first = false;
            continue;
        }
        daysBetween = Days.daysBetween(fromDate, toDate).getDays();
        if (daysBetween > 1 && toDate.isAfterNow()) {
            System.out.println("createSchedule availableDates daysBetween: " + daysBetween);
            PartnerService.createSchedule(sqlSession, product,
                    fromDate.withFieldAdded(DurationFieldType.days(), 1).toDate(),
                    toDate.withFieldAdded(DurationFieldType.days(), -1).toDate(), version);
        }
        fromDate = toDate;
    }
}

From source file:org.cloudata.core.tabletserver.DiskSSTable.java

public Row.Key findMidRowKeyForSplit() throws IOException {
    lock.obtainReadLock();/*from   w ww. j  av  a 2s  . c  om*/

    try {
        //MapFile Index?  Row.Key merge.
        SortedSet<Row.Key> mergedRowKeySet = new TreeSet<Row.Key>();
        int indexRecordCount = 0;
        int mapFileCount = 0;
        for (Map.Entry<String, List<TabletMapFile>> entry : mapFiles.entrySet()) {
            List<TabletMapFile> columnMapFiles = entry.getValue();
            if (columnMapFiles.isEmpty())
                continue;

            for (TabletMapFile columnMapFile : columnMapFiles) {
                mapFileCount++;
                for (MapFileIndexRecord mapFileIndexRecord : columnMapFile.getMapFileIndexRecords()) {
                    mergedRowKeySet.add(mapFileIndexRecord.getRowKey());
                    indexRecordCount++;
                }
            }
        }

        //Split   key .
        int rowRangeSize = mergedRowKeySet.size();

        if (rowRangeSize == 1) {
            ///////////////////////////////////////////////////////////////////////////
            // 
            //        Row.Key previousRowKey = null;
            //        for(Map.Entry<String, List<TabletMapFile>> entry: mapFiles.entrySet()) {
            //          List<TabletMapFile> columnMapFiles = entry.getValue();
            //          if(columnMapFiles.size() == 0)    continue;
            //          
            //          if(columnMapFiles.size() > 1) {
            //            LOG.warn("Map file size > 1 while split:" + tabletInfo.getTabletName());
            //          }
            //          for(TabletMapFile columnMapFile: columnMapFiles) {
            //            for(MapFileIndexRecord mapFileIndexRecord: columnMapFile.getMapFileIndexRecords()) {
            //              Row.Key indexRowKey = mapFileIndexRecord.getRowKey();
            //              if(previousRowKey != null && !indexRowKey.equals(previousRowKey)) {
            //                LOG.debug("Different rowKey:" + indexRowKey);
            //              }
            //              previousRowKey = indexRowKey;
            //            }
            //          }
            //        }
            //End of  
            ///////////////////////////////////////////////////////////////////////////

            return null;
        } else if (rowRangeSize == 2) {
            return mergedRowKeySet.first();
        }

        int count = 0;
        Row.Key midRowKey = null;
        for (Row.Key eachRowKey : mergedRowKeySet) {
            if (count >= (rowRangeSize / 2)) {
                midRowKey = eachRowKey;
                break;
            }
            count++;
        }

        if (midRowKey != null && midRowKey.equals(tabletInfo.getEndRowKey())) {
            LOG.warn("Wrong mid rowkey:");
            for (Row.Key eachRowKey : mergedRowKeySet) {
                LOG.info("MapFile rowKey:" + eachRowKey);
            }
        }
        return midRowKey;
    } finally {
        lock.releaseReadLock();
    }
}

From source file:net.sourceforge.fenixedu.domain.student.Registration.java

public ExecutionYear getFirstCurriculumLineExecutionYear() {
    final SortedSet<ExecutionYear> executionYears = getSortedCurriculumLinesExecutionYears();
    return executionYears.isEmpty() ? null : executionYears.first();
}

From source file:net.sourceforge.fenixedu.domain.student.Registration.java

final public ExecutionYear getFirstEnrolmentExecutionYear() {
    final SortedSet<ExecutionYear> sortedEnrolmentsExecutionYears = getSortedEnrolmentsExecutionYears();
    return sortedEnrolmentsExecutionYears.isEmpty() ? null : sortedEnrolmentsExecutionYears.first();
}