Example usage for java.util SortedMap keySet

List of usage examples for java.util SortedMap keySet

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:pivotal.au.se.gemfirexdweb.controller.QueryController.java

@RequestMapping(value = "/query", method = RequestMethod.POST)
public String worksheetAction(@ModelAttribute("queryAttribute") QueryWindow queryAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/*from   w  w w  .ja  va 2s . co  m*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action SQL from query worksheet");
    logger.info(queryAttribute);

    UserPref userPrefs = (UserPref) session.getAttribute("prefs");

    ConnectionManager cm = ConnectionManager.getInstance();

    if (queryAttribute.getQuery() != null) {

        if (queryAttribute.getSaveWorksheet().equals("Y")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME);

            ServletOutputStream out = response.getOutputStream();
            out.println(queryAttribute.getQuery());
            out.close();
            return null;
        }

        // retrieve connection
        Connection conn = cm.getConnection(session.getId());
        String query = queryAttribute.getQuery().trim();
        logger.debug("Query = " + query);

        String[] splitQueryStr = spiltQuery(query);

        CommandResult result = new CommandResult();

        if (query.length() > 0) {
            if (splitQueryStr.length == 1) {
                String s = checkForComments(query);
                s = s.trim();

                if (determineQueryType(s).equals("SELECT")) {
                    try {
                        final String explain = queryAttribute.getExplainPlan();
                        if (!explain.equals("N")) {
                            logger.debug("Need to run explain plan.");

                            String explainString = "";

                            if (explain.equals("Y")) {
                                explainString = "explain as xml %s";
                            } else if (explain.equals("T")) {
                                explainString = "explain %s";
                            }

                            String xPlan = QueryUtil.runExplainPlan(conn, String.format(explainString, query));
                            logger.debug("received xPath : " + xPlan);

                            if (explain.equals("Y")) {
                                model.addAttribute("explainresult", xPlan);
                            } else if (explain.equals("T")) {
                                model.addAttribute("explaintxtresult", xPlan);
                            }
                        } else {

                            if (queryAttribute.getShowMember().equals("Y")) {
                                String replace = "select dsid() as \"Member\",";

                                s = query.toLowerCase().replaceFirst("select", replace);
                            }

                            long start = System.currentTimeMillis();
                            Result res = QueryUtil.runQuery(conn, s, userPrefs.getMaxRecordsinSQLQueryWindow());
                            long end = System.currentTimeMillis();

                            double timeTaken = new Double(end - start).doubleValue();
                            DecimalFormat df = new DecimalFormat("#.##");

                            model.addAttribute("queryResults", res);
                            model.addAttribute("query", s);
                            model.addAttribute("querysql", s);
                            if (queryAttribute.getQueryCount().equals("Y")) {
                                model.addAttribute("queryResultCount", res.getRowCount());
                            }

                            if (queryAttribute.getElapsedTime().equals("Y")) {
                                model.addAttribute("elapsedTime", df.format(timeTaken / 1000));
                            }

                            addCommandToHistory(session, userPrefs, s);

                        }
                    } catch (Exception ex) {
                        result.setCommand(s);
                        result.setMessage(ex.getMessage() == null ? "Unable to run query" : ex.getMessage());
                        result.setRows(-1);
                        model.addAttribute("result", result);
                        model.addAttribute("query", s);
                    }
                } else {
                    if (s.length() > 0) {
                        if (determineQueryType(s).equals("COMMIT")) {
                            result = QueryUtil.runCommitOrRollback(conn, true, queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        } else if (determineQueryType(s).equals("ROLLBACK")) {
                            result = QueryUtil.runCommitOrRollback(conn, false,
                                    queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        } else if (determineQueryType(s).equals("CALL")) {

                            String procName = getProcName(s);

                            if (procName != null) {
                                String schema = null;

                                int x = procName.indexOf(".");
                                if (x != -1) {
                                    String newProcName = procName.substring((procName.indexOf(".") + 1));
                                    schema = procName.substring(0, (procName.indexOf(".")));
                                    procName = newProcName;
                                } else {
                                    schema = (String) session.getAttribute("schema");
                                }

                                logger.debug("schema for stored procedure = " + schema);
                                logger.debug("call statement called for proc with name " + procName);

                                // need to get schema name to check proc details
                                int numberOfDynamicResultSets = QueryUtil.checkForDynamicResultSetProc(conn,
                                        schema, procName);

                                if (numberOfDynamicResultSets > 0) {
                                    logger.debug("call statement with " + numberOfDynamicResultSets
                                            + " dynamic resultset(s)");
                                    try {
                                        List<Result> procResults = QueryUtil.runStoredprocWithResultSet(conn, s,
                                                userPrefs.getMaxRecordsinSQLQueryWindow(),
                                                numberOfDynamicResultSets);
                                        model.addAttribute("procresults", procResults);
                                        model.addAttribute("callstatement", procName);
                                        model.addAttribute("dynamicresults", numberOfDynamicResultSets);
                                        addCommandToHistory(session, userPrefs, s);
                                    } catch (Exception ex) {
                                        result.setCommand(s);
                                        result.setMessage(ex.getMessage() == null ? "Unable to run query"
                                                : ex.getMessage());
                                        result.setRows(-1);
                                        model.addAttribute("result", result);
                                        model.addAttribute("query", s);
                                    }
                                } else {
                                    result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                                    model.addAttribute("result", result);
                                    if (result.getMessage().startsWith("SUCCESS")) {
                                        addCommandToHistory(session, userPrefs, s);
                                    }
                                }
                            } else {
                                result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                                model.addAttribute("result", result);
                                if (result.getMessage().startsWith("SUCCESS")) {
                                    addCommandToHistory(session, userPrefs, s);
                                }
                            }
                        } else {
                            result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        }

                    }
                }

            } else {
                logger.debug("multiple SQL statements need to be executed");
                SortedMap<String, Object> queryResults = handleMultipleStatements(splitQueryStr, conn,
                        userPrefs, queryAttribute, session);
                logger.debug("keys : " + queryResults.keySet());
                model.addAttribute("sqlResultMap", queryResults);
                model.addAttribute("statementsExecuted", queryResults.size());

            }
        }
    } else {
        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("is multipartcontent request");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> fileItemsList = upload.parseRequest(request);

            logger.debug("fileItemList size = " + fileItemsList.size());
            Iterator<?> it = fileItemsList.iterator();
            while (it.hasNext()) {
                FileItem fileItemTemp = (FileItem) it.next();
                if (fileItemTemp.getFieldName().equals("sqlfilename")) {
                    QueryWindow qw = new QueryWindow();
                    qw.setQuery(fileItemTemp.getString());
                    model.addAttribute("queryAttribute", qw);
                    model.addAttribute("sqlfile", fileItemTemp.getName());
                }
            }
        }
    }

    return "query";
}

From source file:lisong_mechlab.view.graphs.DpsGraph.java

private TableXYDataset getSeries() {
    final Collection<Modifier> modifiers = loadout.getModifiers();
    SortedMap<Weapon, Integer> multiplicity = new TreeMap<Weapon, Integer>(new Comparator<Weapon>() {
        @Override//from  w  w  w .  j a v  a  2s. co m
        public int compare(Weapon aO1, Weapon aO2) {
            int comp = Double.compare(aO2.getRangeMax(modifiers), aO1.getRangeMax(modifiers));
            if (comp == 0)
                return aO1.compareTo(aO2);
            return comp;
        }
    });

    for (Weapon weapon : loadout.items(Weapon.class)) {
        if (!weapon.isOffensive())
            continue;
        if (!multiplicity.containsKey(weapon)) {
            multiplicity.put(weapon, 0);
        }
        int v = multiplicity.get(weapon);
        multiplicity.put(weapon, v + 1);
    }

    List<Weapon> orderedWeapons = new ArrayList<>();
    Double[] ranges = WeaponRanges.getRanges(multiplicity.keySet(), modifiers);
    DefaultTableXYDataset dataset = new DefaultTableXYDataset();
    for (Map.Entry<Weapon, Integer> e : multiplicity.entrySet()) {
        Weapon weapon = e.getKey();
        int mult = e.getValue();

        XYSeries series = new XYSeries(weapon.getName(), true, false);
        for (double range : ranges) {
            final double dps = weapon.getStat("d/s", modifiers);
            final double rangeEff = weapon.getRangeEffectivity(range, modifiers);
            series.add(range, dps * rangeEff * mult);
        }
        dataset.addSeries(series);
        orderedWeapons.add(e.getKey());
    }
    Collections.reverse(orderedWeapons);
    colours.updateColoursToMatch(orderedWeapons);
    return dataset;
}

From source file:org.neo4j.gis.spatial.OsmAnalysisTest.java

public void testAnalysis(String osm, int years, int days) throws Exception {
    Node osmRoot = ReferenceNodes.getReferenceNode(graphDb(), "osm_root");
    Node osmImport = osmRoot.getSingleRelationship(OSMRelation.OSM, Direction.OUTGOING).getEndNode();
    Node usersNode = osmImport.getSingleRelationship(OSMRelation.USERS, Direction.OUTGOING).getEndNode();

    Map<String, User> userIndex = collectUserChangesetData(usersNode);
    SortedSet<User> topTen = getTopTen(userIndex);

    SpatialDatabaseService spatialService = new SpatialDatabaseService(graphDb());
    SortedMap<String, Layer> layers = exportPoints(osm, spatialService, topTen);

    layers = removeEmptyLayers(layers);//from   w  ww  . j av a  2s .  co m
    ReferencedEnvelope bbox = getEnvelope(layers.values());

    StyledImageExporter imageExporter = new StyledImageExporter(graphDb());
    String exportDir = "target/export/" + osm + "/analysis";
    imageExporter.setExportDir(exportDir);
    imageExporter.setZoom(2.0);
    imageExporter.setOffset(-0.05, -0.05);
    imageExporter.setSize(1280, 800);

    for (String layerName : layers.keySet()) {
        SortedMap<String, Layer> layersSubset = new TreeMap<String, Layer>(layers.headMap(layerName));

        String[] to_render = new String[Math.min(10, layersSubset.size() + 1)];
        to_render[0] = layerName;
        if (layersSubset.size() > 0) {
            for (int i = 1; i < to_render.length; i++) {
                String name = layersSubset.lastKey();
                layersSubset.remove(name);
                to_render[i] = name;
            }
        }

        System.out.println("exporting " + layerName);
        imageExporter.saveLayerImage(to_render, // (String[])
                // layersSubset.keySet().toArray(new
                // String[] {}),
                "/Users/davidesavazzi/Desktop/amanzi/awe trial/osm_germany/germany_poi_small.sld",
                new File(layerName + ".png"), bbox);
    }
}

From source file:org.kuali.kra.budget.external.budget.impl.BudgetAdjustmentClientBase.java

/**
 * This method sets the non personnel calculated direct cost.
 * @param accountingLines //from w  ww . j  av a2 s. c o m
 * @return
 */
protected boolean setNonPersonnelCalculatedDirectCostAccountingLines(AwardBudgetDocument awardBudgetDocument,
        Map<String, ScaleTwoDecimal> accountingLines) {
    boolean complete = true;
    Budget currentBudget = awardBudgetDocument.getBudget();
    AwardBudgetExt previousBudget = getPrevBudget(awardBudgetDocument);
    SortedMap<RateType, ScaleTwoDecimal> netExpense = getBudgetAdjustmentServiceHelper()
            .getNonPersonnelCalculatedDirectCost(currentBudget, previousBudget);
    SortedMap<RateType, List<ScaleTwoDecimal>> currentNonPersonnelCalcDirectCost = awardBudgetDocument
            .getAwardBudget().getNonPersonnelCalculatedExpenseTotals();

    for (RateType rateType : netExpense.keySet()) {
        LOG.info("NonPersonnel calculated direct cost: " + rateType.getRateTypeCode() + "-"
                + rateType.getRateClassCode() + " = " + netExpense.get(rateType));

        // check if rate class type is O instead
        if (!rateType.getRateClass().getRateClassTypeCode().equalsIgnoreCase("O")) {
            List<ScaleTwoDecimal> expenses = currentNonPersonnelCalcDirectCost.get(rateType);
            Details details = new Details();
            details.setCurrentAmount(netExpense.get(rateType).toString());
            // only need abs value of amount
            String financialObjectCode = getFinancialObjectCode(awardBudgetDocument,
                    rateType.getRateClassCode(), rateType.getRateTypeCode());
            if (ObjectUtils.isNull(financialObjectCode)) {
                complete &= false;
            } else {
                if (!accountingLines.containsKey(financialObjectCode)) {
                    accountingLines.put(financialObjectCode, netExpense.get(rateType));
                } else {
                    accountingLines.put(financialObjectCode,
                            accountingLines.get(financialObjectCode).add(netExpense.get(rateType)));
                }

            }

        }

    }
    return complete;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.scientificCouncil.credits.ViewTeacherCreditsReportDispatchAction.java

private void setTotals(HttpServletRequest request, ExecutionYear untilExecutionYear,
        SortedMap<Department, Map<ExecutionYear, PeriodCreditsReportDTO>> departmentTotalCredits) {

    int totalTeachersSize = 0, totalCareerTeachersSize = 0, totalNotCareerTeachersSize = 0;
    SortedMap<ExecutionYear, GenericPair<Double, GenericPair<Double, Double>>> executionYearTotals = new TreeMap<ExecutionYear, GenericPair<Double, GenericPair<Double, Double>>>(
            ExecutionYear.COMPARATOR_BY_YEAR);
    for (Department department : departmentTotalCredits.keySet()) {
        for (ExecutionYear executionYear : departmentTotalCredits.get(department).keySet()) {
            if (!executionYearTotals.containsKey(executionYear)) {
                executionYearTotals.put(executionYear, new GenericPair(0.0, new GenericPair(0.0, 0.0)));
            }/*from w w w.  j  a va2 s. c  o  m*/

            GenericPair genericPair = executionYearTotals.get(executionYear);
            genericPair.setLeft(round(departmentTotalCredits.get(department).get(executionYear).getCredits()
                    + executionYearTotals.get(executionYear).getLeft()));
            ((GenericPair) genericPair.getRight()).setLeft(round(
                    departmentTotalCredits.get(department).get(executionYear).getCareerCategoryTeacherCredits()
                            + executionYearTotals.get(executionYear).getRight().getLeft()));
            ((GenericPair) genericPair.getRight()).setRight(round(departmentTotalCredits.get(department)
                    .get(executionYear).getNotCareerCategoryTeacherCredits()
                    + executionYearTotals.get(executionYear).getRight().getRight()));

            if (executionYear.equals(untilExecutionYear)) {
                totalTeachersSize += departmentTotalCredits.get(department).get(executionYear)
                        .getTeachersSize();
                totalCareerTeachersSize += departmentTotalCredits.get(department).get(executionYear)
                        .getCareerTeachersSize();
                totalNotCareerTeachersSize += departmentTotalCredits.get(department).get(executionYear)
                        .getNotCareerTeachersSize();
            }
        }
    }

    request.setAttribute("totalCareerTeachersSize", totalCareerTeachersSize);
    request.setAttribute("totalNotCareerTeachersSize", totalNotCareerTeachersSize);
    request.setAttribute("totalCareerTeachersBalance",
            round(executionYearTotals.get(untilExecutionYear).getRight().getLeft() / totalCareerTeachersSize));
    request.setAttribute("totalNotCareerTeachersBalance", round(
            executionYearTotals.get(untilExecutionYear).getRight().getRight() / totalNotCareerTeachersSize));
    request.setAttribute("totalBalance",
            round(executionYearTotals.get(untilExecutionYear).getLeft() / totalTeachersSize));
    request.setAttribute("totalTeachersSize", totalTeachersSize);
    request.setAttribute("executionYearTotals", executionYearTotals);
}

From source file:org.hyperic.hq.product.server.session.ProductManagerImpl.java

private void createAlertDefinitions(final PluginInfo pInfo) throws VetoException {
    final InputStream alertDefns = pInfo.resourceLoader.getResourceAsStream(ALERT_DEFINITIONS_XML_FILE);
    if (alertDefns == null) {
        return;//from   w w w .  j  a v a 2s  . c  o  m
    }
    try {
        final Set<AlertDefinitionValue> alertDefs = alertDefinitionXmlParser.parse(alertDefns);
        for (AlertDefinitionValue alertDefinition : alertDefs) {
            try {
                final AppdefEntityID id = new AppdefEntityID(alertDefinition.getAppdefType(),
                        alertDefinition.getAppdefId());
                final SortedMap<String, Integer> existingAlertDefinitions = alertDefinitionManager
                        .findAlertDefinitionNames(id, EventConstants.TYPE_ALERT_DEF_ID);
                // TODO update existing alert defs - for now, just create if
                // one does not exist. Be aware that this method is also
                // called
                // when new service type metadata is discovered (from
                // updateServiceTypes method), as well as when a new or
                // modified plugin jar is detected
                if (!(existingAlertDefinitions.keySet().contains(alertDefinition.getName()))) {
                    alertDefinitionManager.createAlertDefinition(alertDefinition);
                }
            } catch (Exception e) {
                log.error("Unable to load some or all of alert definitions for plugin " + pInfo.name
                        + ".  Cause: " + e.getMessage());
            }
        }
    } catch (Exception e) {
        log.error("Unable to parse alert definitions for plugin " + pInfo.name + ".  Cause: " + e.getMessage());
    } finally {
        try {
            alertDefns.close();
        } catch (IOException e) {
            log.warn("Error closing InputStream to alert definitions file of plugin " + pInfo.name
                    + ".  Cause: " + e.getMessage());
        }
    }
}

From source file:org.apache.james.mailbox.store.StoreMessageManager.java

/**
 * Copy the {@link MessageRange} to the {@link StoreMessageManager}
 * // w w  w .ja va  2  s.c o  m
 * @param set
 * @param toMailbox
 * @param session
 * @throws MailboxException
 */
public List<MessageRange> copyTo(final MessageRange set, final StoreMessageManager toMailbox,
        final MailboxSession session) throws MailboxException {
    if (!toMailbox.isWriteable(session)) {
        throw new ReadOnlyException(new StoreMailboxPath(toMailbox.getMailboxEntity()),
                session.getPathDelimiter());
    }

    return locker.executeWithLock(session, new StoreMailboxPath(toMailbox.getMailboxEntity()),
            new MailboxPathLocker.LockAwareExecution<List<MessageRange>>() {

                @Override
                public List<MessageRange> execute() throws MailboxException {
                    SortedMap<Long, MessageMetaData> copiedUids = copy(set, toMailbox, session);
                    dispatcher.added(session, copiedUids, toMailbox.getMailboxEntity());
                    return MessageRange.toRanges(new ArrayList<Long>(copiedUids.keySet()));
                }
            }, true);
}

From source file:org.apache.james.mailbox.store.StoreMessageManager.java

/**
 * Move the {@link MessageRange} to the {@link StoreMessageManager}
 * //from  w  w  w . j  ava 2  s.com
 * @param set
 * @param toMailbox
 * @param session
 * @throws MailboxException
 */
public List<MessageRange> moveTo(final MessageRange set, final StoreMessageManager toMailbox,
        final MailboxSession session) throws MailboxException {
    if (!isWriteable(session)) {
        throw new ReadOnlyException(getMailboxPath(), session.getPathDelimiter());
    }
    if (!toMailbox.isWriteable(session)) {
        throw new ReadOnlyException(new StoreMailboxPath(toMailbox.getMailboxEntity()),
                session.getPathDelimiter());
    }

    //TODO lock the from mailbox too, in a non-deadlocking manner - how?
    return locker.executeWithLock(session, new StoreMailboxPath(toMailbox.getMailboxEntity()),
            new MailboxPathLocker.LockAwareExecution<List<MessageRange>>() {

                @Override
                public List<MessageRange> execute() throws MailboxException {
                    SortedMap<Long, MessageMetaData> movedUids = move(set, toMailbox, session);
                    dispatcher.added(session, movedUids, toMailbox.getMailboxEntity());
                    return MessageRange.toRanges(new ArrayList<Long>(movedUids.keySet()));
                }
            }, true);
}

From source file:org.mule.devkit.doclet.Doclava.java

public static void writeLists() {
    Data data = makeHDF();/*  w w w  . j a v a  2s  .  c  om*/

    ClassInfo[] classes = Converter.rootClasses();

    SortedMap<String, Object> sorted = new TreeMap<String, Object>();
    for (ClassInfo cl : classes) {
        if (cl.isHidden()) {
            continue;
        }
        sorted.put(cl.qualifiedName(), cl);
        PackageInfo pkg = cl.containingPackage();
        String name;
        if (pkg == null) {
            name = "";
        } else {
            name = pkg.name();
        }
        sorted.put(name, pkg);
        for (MethodInfo method : cl.methods()) {
            if (method.isProcessor() || method.isSource() || method.isTransformer()) {
                sorted.put(method.elementName(), method);
            }
        }
    }

    int i = 0;
    for (String s : sorted.keySet()) {
        data.setValue("docs.pages." + i + ".id", "" + i);
        data.setValue("docs.pages." + i + ".label", s);

        Object o = sorted.get(s);
        if (o instanceof PackageInfo) {
            PackageInfo pkg = (PackageInfo) o;
            data.setValue("docs.pages." + i + ".link", "java/" + pkg.htmlPage());
            data.setValue("docs.pages." + i + ".type", "package");
        } else if (o instanceof ClassInfo) {
            ClassInfo cl = (ClassInfo) o;
            data.setValue("docs.pages." + i + ".link", "java/" + cl.htmlPage());
            data.setValue("docs.pages." + i + ".type", "class");
        } else if (o instanceof MethodInfo) {
            MethodInfo mi = (MethodInfo) o;
            data.setValue("docs.pages." + i + ".id", "" + i);
            data.setValue("docs.pages." + i + ".link", "mule/" + mi.relativeModulePath());
            data.setValue("docs.pages." + i + ".type", "method");
        }
        i++;
    }

    ClearPage.write(data, "lists.cs", javadocDir + "lists.js");
}

From source file:org.wrml.runtime.schema.Prototype.java

/**
 * Creates a new Prototype to represent the identified schema.
 *
 * @param schemaLoader The schema loader for this prototype's schema.
 * @param schemaUri    The schema identifier.
 * @throws PrototypeException Thrown if there are problems with the initial prototyping of the schema.
 *//*from w w  w  .  jav a2s .  co m*/
Prototype(final SchemaLoader schemaLoader, final URI schemaUri) throws PrototypeException {

    LOGGER.debug("Creating Prototype for schema ID: {}", new Object[] { schemaUri });

    _SchemaLoader = schemaLoader;
    if (_SchemaLoader == null) {

        throw new PrototypeException("The SchemaLoader parameter value cannot be *null*.", null, this);
    }

    _SchemaUri = schemaUri;
    if (_SchemaUri == null) {
        throw new PrototypeException("The undefined (aka *null*) schema can not be prototyped.", null, this);
    }

    if (schemaUri.equals(schemaLoader.getResourceTemplateSchemaUri())) {
        LOGGER.debug("Creating Prototype for ResourceTemplate");
    }

    _UniqueName = new UniqueName(_SchemaUri);

    //
    // Use the SchemaLoader and the schema uri to get the schema's Java Class
    // representation.
    //
    final Class<?> schemaInterface = getSchemaInterface();

    if (ValueType.JAVA_TYPE_ABSTRACT.equals(schemaInterface)) {
        _IsAbstract = true;
    } else if (Document.class.equals(schemaInterface)) {
        _IsDocument = true;
    }

    //
    // Introspect the associated class, extracting metadata from the parent
    // schema's Java interfaces (up to but not including the Model
    // interface).
    //

    _SchemaBean = new JavaBean(schemaInterface, ValueType.JAVA_TYPE_MODEL, LinkSlot.class);
    _AllBaseSchemaUris = new LinkedHashSet<>();
    _BaseSchemaUris = new LinkedHashSet<>();
    _AllSlotNames = new TreeSet<>();
    _ProtoSlots = new TreeMap<>();
    _CollectionPropertyProtoSlots = new TreeMap<>();
    _LinkRelationUris = new TreeMap<>();

    _LinkProtoSlots = new TreeMap<>();
    _SlotAliases = new TreeMap<>();
    _SearchableSlots = new TreeSet<>();

    // initBaseSchemas(...)
    {

        //
        // Use Java reflection to get all implemented interfaces and then turn
        // them into schema ids. With reflection we get de-duplication and
        // recursive traversal for free.
        //

        final List<Class<?>> allBaseInterfaces = ClassUtils.getAllInterfaces(schemaInterface);
        // Loop backwards to achieve desired key mapping precedence/overriding
        for (final Class<?> baseInterface : allBaseInterfaces) {

            if (ValueType.isSchemaInterface(baseInterface) && (baseInterface != ValueType.JAVA_TYPE_MODEL)) {

                final URI baseSchemaUri = _SchemaLoader.getTypeUri(baseInterface);
                _AllBaseSchemaUris.add(baseSchemaUri);

                if (Document.class.equals(baseInterface)) {
                    _IsDocument = true;
                }

                if (AggregateDocument.class.equals(baseInterface)) {
                    _IsAggregate = true;
                }

            }

        }

        // Store the immediate base schemas as well

        final Class<?>[] baseInterfaces = schemaInterface.getInterfaces();
        if (baseInterfaces != null) {

            for (final Class<?> baseInterface : baseInterfaces) {
                if (ValueType.isSchemaInterface(baseInterface)
                        && (baseInterface != ValueType.JAVA_TYPE_MODEL)) {
                    final URI baseSchemaUri = _SchemaLoader.getTypeUri(baseInterface);
                    _BaseSchemaUris.add(baseSchemaUri);
                }

                if (ValueType.JAVA_TYPE_ABSTRACT.equals(baseInterface)) {
                    _IsAbstract = true;
                }
            }

        }

    } // End of base schema init

    // initKeys(...)
    {
        final WRML wrml = schemaInterface.getAnnotation(WRML.class);
        if (wrml != null) {
            final String[] keySlotNameArray = wrml.keySlotNames();

            if ((keySlotNameArray != null) && (keySlotNameArray.length > 0)) {

                _KeySlotNames = new TreeSet<>(Arrays.asList(keySlotNameArray));

                if (_KeySlotNames.size() == 1) {
                    final String keySlotName = _KeySlotNames.first();
                    final Property property = _SchemaBean.getProperties().get(keySlotName);
                    if (property != null) {
                        _KeyType = property.getType();
                    } else {
                        throw new PrototypeException("The named key slot, \"" + keySlotName
                                + "\", is not defined for Schema: " + schemaUri + ".", null, this);
                    }
                } else {

                    // Schemas with Keys that use more than one slot value to
                    // determine uniqueness use the CompositeKey type (at
                    // runtime) as their key object.
                    //
                    _KeyType = ValueType.JAVA_TYPE_COMPOSITE_KEY;
                }

            }

            final String[] comparableSlotNameArray = wrml.comparableSlotNames();

            if ((comparableSlotNameArray != null) && (comparableSlotNameArray.length > 0)) {

                _ComparableSlotNames = new LinkedHashSet<String>(Arrays.asList(comparableSlotNameArray));
            }

            final String titleSlotName = wrml.titleSlotName();
            if (StringUtils.isNotBlank(titleSlotName)) {
                _TitleSlotName = titleSlotName;
            }

        }

    } // End of the key initialization

    // initMiscAnnotations(...)
    {

        final Description schemaDescription = schemaInterface.getAnnotation(Description.class);
        if (schemaDescription != null) {
            _Description = schemaDescription.value();
        } else {
            _Description = null;
        }

        final Title schemaTitle = schemaInterface.getAnnotation(Title.class);
        if (schemaTitle != null) {
            _Title = schemaTitle.value();
        } else {
            _Title = schemaInterface.getSimpleName();
        }

        final ThumbnailImage thumbnailImage = schemaInterface.getAnnotation(ThumbnailImage.class);
        if (thumbnailImage != null) {
            _ThumbnailLocation = URI.create(thumbnailImage.value());
        } else {
            _ThumbnailLocation = null;
        }

        _ReadOnly = (schemaInterface.getAnnotation(ReadOnly.class) != null) ? true : false;

        final Version schemaVersion = schemaInterface.getAnnotation(Version.class);
        if (schemaVersion != null) {
            _Version = schemaVersion.value();
        } else {
            // TODO: Look for the "static final long serialVersionUID" ?
            _Version = 1L;
        }

        final Tags tags = schemaInterface.getAnnotation(Tags.class);
        if (tags != null) {
            final String[] tagArray = tags.value();

            if ((tagArray != null) && (tagArray.length > 0)) {

                _Tags = new TreeSet<String>(Arrays.asList(tagArray));
            }
        }

    } // End of annotation-based initialization

    // initPropertySlots(...)
    {
        final Map<String, Property> properties = _SchemaBean.getProperties();

        for (final String slotName : properties.keySet()) {
            final Property property = properties.get(slotName);

            final PropertyProtoSlot propertyProtoSlot;

            final CollectionSlot collectionSlot = property.getAnnotation(CollectionSlot.class);
            if (collectionSlot != null) {
                propertyProtoSlot = new CollectionPropertyProtoSlot(this, slotName, property);
            } else {
                propertyProtoSlot = new PropertyProtoSlot(this, slotName, property);
            }

            addProtoSlot(propertyProtoSlot);
        }
    }

    // initLinkSlots(...)
    {

        //
        // Map the the schema bean's "other" (non-Property) methods.
        //

        final SortedMap<String, SortedSet<JavaMethod>> otherMethods = _SchemaBean.getOtherMethods();
        final Set<String> otherMethodNames = otherMethods.keySet();

        for (final String methodName : otherMethodNames) {

            final SortedSet<JavaMethod> methodSet = otherMethods.get(methodName);
            if (methodSet.size() != 1) {
                throw new PrototypeException("The link method: " + methodName + " cannot be overloaded.", this);
            }

            final JavaMethod javaMethod = methodSet.first();
            final Method method = javaMethod.getMethod();

            final LinkSlot linkSlot = method.getAnnotation(LinkSlot.class);
            if (linkSlot == null) {
                throw new PrototypeException("The method: " + javaMethod + " is not a link method", null, this);
            }

            final String relationUriString = linkSlot.linkRelationUri();
            final URI linkRelationUri = URI.create(relationUriString);

            if (_LinkProtoSlots.containsKey(linkRelationUri)) {
                throw new PrototypeException(
                        "A schema cannot use the same link relation for more than one method. Duplicate link relation: "
                                + linkRelationUri + " found in link method: " + javaMethod,
                        this);
            }

            final org.wrml.model.rest.Method relMethod = linkSlot.method();

            String slotName = methodName;
            if (relMethod == org.wrml.model.rest.Method.Get && slotName.startsWith(JavaBean.GET)) {
                slotName = slotName.substring(3);
                slotName = Character.toLowerCase(slotName.charAt(0)) + slotName.substring(1);
            }
            _LinkRelationUris.put(slotName, linkRelationUri);

            if (_ProtoSlots.containsKey(slotName)) {
                throw new PrototypeException(
                        "A schema cannot use the same name for more than one slot. Duplicate slot name: "
                                + slotName + " found in link method: " + javaMethod,
                        this);
            }

            final LinkProtoSlot linkProtoSlot = new LinkProtoSlot(this, slotName, javaMethod);

            if ((linkProtoSlot.isEmbedded() || isAggregate())
                    && (relMethod == org.wrml.model.rest.Method.Get)) {
                _ContainsEmbeddedLink = true;
            }

            _LinkProtoSlots.put(linkRelationUri, linkProtoSlot);

            addProtoSlot(linkProtoSlot);

        }

    } // End of link slot init

    if (!_SlotAliases.isEmpty()) {
        for (final String alias : _SlotAliases.keySet()) {
            final ProtoSlot protoSlot = _ProtoSlots.get(alias);
            protoSlot.setAlias(true);
            final String realName = _SlotAliases.get(alias);
            protoSlot.setRealName(realName);

        }
    }

}