Example usage for org.apache.commons.collections.map ListOrderedMap size

List of usage examples for org.apache.commons.collections.map ListOrderedMap size

Introduction

In this page you can find the example usage for org.apache.commons.collections.map ListOrderedMap size.

Prototype

public int size() 

Source Link

Usage

From source file:com.doculibre.constellio.stats.StatsCompiler.java

public String createQuery(ListOrderedMap m_queries) {
    StringBuilder sb = new StringBuilder();
    int i = 0;//w w  w  .j a v  a  2s. com
    for (Object s : m_queries.keyList()) {
        if ((i > 0) && (m_queries.size() > 1)) {
            sb.append(" ");
        }
        sb.append(s);

        i++;
    }
    return sb.toString();
}

From source file:com.doculibre.constellio.wicket.pages.SearchResultsPage.java

private void initComponents() {
    final SimpleSearch simpleSearch = getSimpleSearch();
    String collectionName = simpleSearch.getCollectionName();
    ConstellioUser currentUser = ConstellioSession.get().getUser();
    RecordCollectionServices recordCollectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection collection = recordCollectionServices.get(collectionName);
    boolean userHasPermission = false;
    if (collection != null) {
        userHasPermission = (!collection.hasSearchPermission())
                || (currentUser != null && currentUser.hasSearchPermission(collection));
    }//from   w  w w.j  a  v a 2  s  .  c o  m
    if (StringUtils.isEmpty(collectionName) || !userHasPermission) {
        setResponsePage(ConstellioApplication.get().getHomePage());
    } else {

        final IModel suggestedSearchKeyListModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                ListOrderedMap suggestedSearch = new ListOrderedMap();
                if (simpleSearch.isQueryValid() && simpleSearch.getQuery() != null) {
                    SpellChecker spellChecker = new SpellChecker(ConstellioApplication.get().getDictionaries());
                    try {
                        if (!simpleSearch.getQuery().equals("*:*")) {
                            suggestedSearch = spellChecker.suggest(simpleSearch.getQuery(),
                                    simpleSearch.getCollectionName());
                        }
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                        // chec du spellchecker, pas besoin de faire planter la page
                    }
                }
                return suggestedSearch;
            }
        };

        BaseSearchResultsPageHeaderPanel headerPanel = (BaseSearchResultsPageHeaderPanel) getHeaderComponent();
        headerPanel.setAdvancedForm(simpleSearch.getAdvancedSearchRule() != null);
        SearchFormPanel searchFormPanel = headerPanel.getSearchFormPanel();

        final ThesaurusSuggestionPanel thesaurusSuggestionPanel = new ThesaurusSuggestionPanel(
                "thesaurusSuggestion", simpleSearch, getLocale());
        add(thesaurusSuggestionPanel);

        SpellCheckerPanel spellCheckerPanel = new SpellCheckerPanel("spellChecker",
                searchFormPanel.getSearchTxtField(), searchFormPanel.getSearchButton(),
                suggestedSearchKeyListModel) {
            @SuppressWarnings("unchecked")
            public boolean isVisible() {
                boolean visible = false;
                if (dataProvider != null && !thesaurusSuggestionPanel.isVisible()) {
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(simpleSearch.getCollectionName());
                    if (collection != null && collection.isSpellCheckerActive()
                            && simpleSearch.getAdvancedSearchRule() == null) {
                        ListOrderedMap spell = (ListOrderedMap) suggestedSearchKeyListModel.getObject();
                        if (spell.size() > 0/* && dataProvider.size() == 0 */) {
                            for (String key : (List<String>) spell.keyList()) {
                                if (spell.get(key) != null) {
                                    return visible = true;
                                }
                            }
                        }
                    }
                }
                return visible;
            }
        };
        add(spellCheckerPanel);

        dataProvider = new SearchResultsDataProvider(simpleSearch, 10);

        WebMarkupContainer searchResultsSection = new WebMarkupContainer("searchResultsSection") {
            @Override
            public boolean isVisible() {
                return StringUtils.isNotBlank(simpleSearch.getLuceneQuery());
            }
        };
        add(searchResultsSection);

        IModel detailsLabelModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                String detailsLabel;
                QueryResponse queryResponse = dataProvider.getQueryResponse();
                long start;
                long nbRes;
                double elapsedTimeSeconds;
                if (queryResponse != null) {
                    start = queryResponse.getResults().getStart();
                    nbRes = dataProvider.size();
                    elapsedTimeSeconds = (double) queryResponse.getElapsedTime() / 1000;
                } else {
                    start = 0;
                    nbRes = 0;
                    elapsedTimeSeconds = 0;
                }
                long end = start + 10;
                if (nbRes < end) {
                    end = nbRes;
                }

                String pattern = "#.####";
                DecimalFormat elapsedTimeFormatter = new DecimalFormat(pattern);
                String elapsedTimeStr = elapsedTimeFormatter.format(elapsedTimeSeconds);

                String forTxt = new StringResourceModel("for", SearchResultsPage.this, null).getString();
                String noResultTxt = new StringResourceModel("noResult", SearchResultsPage.this, null)
                        .getString();
                String resultsTxt = new StringResourceModel("results", SearchResultsPage.this, null)
                        .getString();
                String ofTxt = new StringResourceModel("of", SearchResultsPage.this, null).getString();
                String secondsTxt = new StringResourceModel("seconds", SearchResultsPage.this, null)
                        .getString();

                String queryTxt = " ";
                if (simpleSearch.isQueryValid() && simpleSearch.getQuery() != null
                        && simpleSearch.getAdvancedSearchRule() == null) {
                    queryTxt = " " + forTxt + " " + simpleSearch.getQuery() + " ";
                }

                if (nbRes > 0) {
                    Locale locale = getLocale();
                    detailsLabel = resultsTxt + " " + NumberFormatUtils.format(start + 1, locale) + " - "
                            + NumberFormatUtils.format(end, locale) + " " + ofTxt + " "
                            + NumberFormatUtils.format(nbRes, locale) + queryTxt + "(" + elapsedTimeStr + " "
                            + secondsTxt + ")";
                } else {
                    detailsLabel = noResultTxt + " " + queryTxt + "(" + elapsedTimeStr + " " + secondsTxt + ")";
                }

                String collectionName = dataProvider.getSimpleSearch().getCollectionName();
                if (collectionName != null) {
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(collectionName);
                    Locale displayLocale = collection.getDisplayLocale(getLocale());
                    String collectionTitle = collection.getTitle(displayLocale);
                    detailsLabel = collectionTitle + " > " + detailsLabel;
                }
                return detailsLabel;
            }
        };
        Label detailsLabel = new Label("detailsRes", detailsLabelModel);
        add(detailsLabel);

        final IModel sortOptionsModel = new LoadableDetachableModel() {

            @Override
            protected Object load() {
                List<SortChoice> choices = new ArrayList<SortChoice>();
                choices.add(new SortChoice(null, null, null));
                String collectionName = dataProvider.getSimpleSearch().getCollectionName();
                if (collectionName != null) {
                    IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(collectionName);
                    for (IndexField indexField : indexFieldServices.getSortableIndexFields(collection)) {
                        String label = indexField.getLabel(IndexField.LABEL_TITLE,
                                ConstellioSession.get().getLocale());
                        if (label == null || label.isEmpty()) {
                            label = indexField.getName();
                        }
                        choices.add(new SortChoice(indexField.getName(), label, "asc"));
                        choices.add(new SortChoice(indexField.getName(), label, "desc"));
                    }
                }
                return choices;
            }
        };

        IChoiceRenderer triChoiceRenderer = new ChoiceRenderer() {
            @Override
            public Object getDisplayValue(Object object) {
                SortChoice choice = (SortChoice) object;
                String displayValue;
                if (choice.title == null) {
                    displayValue = new StringResourceModel("sort.relevance", SearchResultsPage.this, null)
                            .getString();
                } else {
                    String order = new StringResourceModel("sortOrder." + choice.order, SearchResultsPage.this,
                            null).getString();
                    displayValue = choice.title + " " + order;
                }
                return displayValue;
            }
        };
        IModel value = new Model(new SortChoice(simpleSearch.getSortField(), simpleSearch.getSortField(),
                simpleSearch.getSortOrder()));
        DropDownChoice sortField = new DropDownChoice("sortField", value, sortOptionsModel, triChoiceRenderer) {
            @Override
            protected boolean wantOnSelectionChangedNotifications() {
                return true;
            }

            @Override
            protected void onSelectionChanged(Object newSelection) {
                SortChoice choice = (SortChoice) newSelection;
                if (choice.name == null) {
                    simpleSearch.setSortField(null);
                    simpleSearch.setSortOrder(null);
                } else {
                    simpleSearch.setSortField(choice.name);
                    simpleSearch.setSortOrder(choice.order);
                }
                simpleSearch.setPage(0);

                PageFactoryPlugin pageFactoryPlugin = PluginFactory.getPlugin(PageFactoryPlugin.class);
                RequestCycle.get().setResponsePage(pageFactoryPlugin.getSearchResultsPage(),
                        SearchResultsPage.getParameters(simpleSearch));
            }

            @Override
            public boolean isVisible() {
                return ((List<?>) sortOptionsModel.getObject()).size() > 1;
            }
        };
        searchResultsSection.add(sortField);
        sortField.setNullValid(false);

        add(new AjaxLazyLoadPanel("facetsPanel") {
            @Override
            public Component getLazyLoadComponent(String markupId) {
                return new FacetsPanel(markupId, dataProvider);
            }
        });

        final IModel featuredLinkModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink suggestion;
                RecordCollectionServices collectionServices = ConstellioSpringUtils
                        .getRecordCollectionServices();
                FeaturedLinkServices featuredLinkServices = ConstellioSpringUtils.getFeaturedLinkServices();
                Long featuredLinkId = simpleSearch.getFeaturedLinkId();
                if (featuredLinkId != null) {
                    suggestion = featuredLinkServices.get(featuredLinkId);
                } else {
                    String collectionName = simpleSearch.getCollectionName();
                    if (simpleSearch.getAdvancedSearchRule() == null) {
                        String text = simpleSearch.getQuery();
                        RecordCollection collection = collectionServices.get(collectionName);
                        suggestion = featuredLinkServices.suggest(text, collection);
                        if (suggestion == null) {
                            SynonymServices synonymServices = ConstellioSpringUtils.getSynonymServices();
                            List<String> synonyms = synonymServices.getSynonyms(text, collectionName);
                            if (!synonyms.isEmpty()) {
                                for (String synonym : synonyms) {
                                    if (!synonym.equals(text)) {
                                        suggestion = featuredLinkServices.suggest(synonym, collection);
                                    }
                                    if (suggestion != null) {
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        suggestion = new FeaturedLink();
                    }
                }
                return suggestion;
            }
        };
        IModel featuredLinkTitleModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink featuredLink = (FeaturedLink) featuredLinkModel.getObject();
                return featuredLink.getTitle(getLocale());
            }
        };
        final IModel featuredLinkDescriptionModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink featuredLink = (FeaturedLink) featuredLinkModel.getObject();
                StringBuffer descriptionSB = new StringBuffer();
                String description = featuredLink.getDescription(getLocale());
                if (description != null) {
                    descriptionSB.append(description);
                    String lookFor = "${";
                    int indexOfLookFor = -1;
                    while ((indexOfLookFor = descriptionSB.indexOf(lookFor)) != -1) {
                        int indexOfEnclosingQuote = descriptionSB.indexOf("}", indexOfLookFor);
                        String featuredLinkIdStr = descriptionSB.substring(indexOfLookFor + lookFor.length(),
                                indexOfEnclosingQuote);

                        int indexOfTagBodyStart = descriptionSB.indexOf(">", indexOfEnclosingQuote) + 1;
                        int indexOfTagBodyEnd = descriptionSB.indexOf("</a>", indexOfTagBodyStart);
                        String capsuleQuery = descriptionSB.substring(indexOfTagBodyStart, indexOfTagBodyEnd);
                        if (capsuleQuery.indexOf("<br/>") != -1) {
                            capsuleQuery = StringUtils.remove(capsuleQuery, "<br/>");
                        }
                        if (capsuleQuery.indexOf("<br />") != -1) {
                            capsuleQuery = StringUtils.remove(capsuleQuery, "<br />");
                        }

                        try {
                            String linkedCapsuleURL = getFeaturedLinkURL(new Long(featuredLinkIdStr));
                            descriptionSB.replace(indexOfLookFor, indexOfEnclosingQuote + 1, linkedCapsuleURL);
                        } catch (NumberFormatException e) {
                            // Ignore
                        }
                    }
                }
                return descriptionSB.toString();
            }

            private String getFeaturedLinkURL(Long featuredLinkId) {
                SimpleSearch clone = simpleSearch.clone();
                clone.setFeaturedLinkId(featuredLinkId);
                PageFactoryPlugin pageFactoryPlugin = PluginFactory.getPlugin(PageFactoryPlugin.class);
                String url = RequestCycle.get()
                        .urlFor(pageFactoryPlugin.getSearchResultsPage(), getParameters(clone)).toString();
                return url;
            }
        };

        WebMarkupContainer featuredLink = new WebMarkupContainer("featuredLink", featuredLinkModel) {
            @Override
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    if (featuredLinkModel.getObject() != null) {
                        String description = (String) featuredLinkDescriptionModel.getObject();
                        visible = StringUtils.isNotEmpty(description);
                    } else {
                        visible = false;
                    }
                }
                DataView dataView = (DataView) searchResultsPanel.getDataView();
                return visible && dataView.getCurrentPage() == 0;
            }
        };
        searchResultsSection.add(featuredLink);
        featuredLink.add(new Label("title", featuredLinkTitleModel));
        featuredLink.add(new WebMarkupContainer("description", featuredLinkDescriptionModel) {
            @Override
            protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
                String descriptionHTML = (String) getModel().getObject();
                replaceComponentTagBody(markupStream, openTag, descriptionHTML);
            }
        });

        searchResultsSection
                .add(searchResultsPanel = new SearchResultsPanel("resultatsRecherchePanel", dataProvider));
    }
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.MetaThesaurusToSQL.java

/**
 * Adds qualification to concepts and associations in the LexGrid
 * repository./*from  www.  jav a  2s.  c o m*/
 * 
 * @param aq
 *            Qualification information from the UMLS source.
 * @param constructHCD
 *            Indicates whether artificial context values should be
 *            constructed if not provided in the UMLS information.
 * @param rela
 *            The relationship attribute defined by UMLS (can be empty or
 *            null).
 * @param totalCount
 *            The total number of context links qualified previously.
 * @return The number of contextual links qualified in the repository for
 *         the given UMLS info.
 * @throws SQLException
 */
protected int loadContext(AssociationQualification aq, boolean constructHCD, String rela, int totalCount)
        throws SQLException {
    // If a context identifier was assigned, use it.
    // If a context identifier is not assigned and the option to construct
    // is enabled,
    // derive one based on the root concept code and path to root AUI
    // values.
    int contextLinks = 0;
    String hcd = aq.qualifierValue;
    if (constructHCD && StringUtils.isBlank(hcd) && StringUtils.isNotBlank(aq.pathToRoot)
            && StringUtils.isNotBlank(aq.sourceConceptCode)) {
        MessageDigest md = getSHA1();
        md.reset();
        md.update(aq.pathToRoot.getBytes());
        hcd = String.valueOf(md.digest(aq.sourceConceptCode.getBytes()));
    }
    if (StringUtils.isBlank(hcd))
        return 0;

    // Iterate through the path to root and determine the codes for
    // participating AUIs. We maintain a LRU cache of AUIs to codes to
    // assist.
    // If the associated code is not in the cache, find and cache it here.
    ListOrderedMap orderedPtrAUIToCode = new ListOrderedMap();

    // Break up the path to root into AUIs ...
    String[] auis = aq.pathToRoot.split("\\.");
    if (auis.length > 0) {
        // Check the cache for each. If not found, perform and cache the
        // AUI to code mapping.
        PreparedStatement getPTRCode = umlsConnection2_
                .prepareStatement("SELECT CUI FROM MRCONSO WHERE AUI = ?");
        try {
            String nextCode, nextAUI;
            for (int i = 0; i < auis.length; i++) {
                // Check for registered code in the cache.
                nextAUI = auis[i];
                nextCode = (String) auiToCodeCache_.get(nextAUI);

                // If not cached, perform lookup ...
                if (nextCode == null) {
                    getPTRCode.setString(1, nextAUI);
                    ResultSet ptrCodes = getPTRCode.executeQuery();
                    int count = 0;
                    try {
                        while (ptrCodes.next()) {
                            count++;
                            nextCode = ptrCodes.getString(1);
                        }
                    } finally {
                        ptrCodes.close();
                    }
                    // If one to one mapping (probably should always be, but
                    // doesn't
                    // hurt to check), add to the cache for quick lookup
                    // later...
                    if (count == 1)
                        auiToCodeCache_.put(nextAUI, nextCode);
                }

                // Was it resolved?
                if (nextCode != null)
                    orderedPtrAUIToCode.put(nextAUI, nextCode);
            }
        } finally {
            getPTRCode.close();
        }
    }
    // Ensure we have included the original AUI to code mapping from the
    // provided UMLS qualification info; inserted last as the root
    // of the path.
    orderedPtrAUIToCode.put(aq.sourceConceptAUI, aq.sourceConceptCode);

    // /////////////////////////////////////////////////////////////////////
    // We have all the participating codes and AUIs.
    // Add context qualifiers to the text presentation of each concept
    // based on code/AUI pairs.
    // /////////////////////////////////////////////////////////////////////
    for (OrderedMapIterator omi = orderedPtrAUIToCode.orderedMapIterator(); omi.hasNext();) {
        omi.next();
        String aui = (String) omi.getKey();
        String code = (String) omi.getValue();
        if (code != null)
            qualifyConceptPresentation(code, aui, aq.codingSchemeName, aq.qualifierName, hcd);
    }

    // /////////////////////////////////////////////////////////////////////
    // At this point we have taken care of all the concept qualifiers.
    // Now find and similarly tag each participating association link
    // between AUIs in the path to root chain.
    // /////////////////////////////////////////////////////////////////////

    // Statements to find LexGrid association to concept mappings.
    // Check source to target (parent association as processed)
    // or target to source (child association as processed).

    // Honor the association specified in the MRHIER entry, if provided.
    // For example, the UMLS 'inverse_isa' is mapped on load to 'hasSubtype'
    // association name; account for that here.
    String assoc = mapRela(rela);

    // If a specific relation attribute (rela) was not provided, consider
    // all relevant
    // hierarchical associations (including UMLS standard or source-specific
    // names).
    String assocParam = StringUtils.isNotBlank(assoc) ? '\'' + assoc + '\''
            : toCommaDelimitedWithQuotes(getHierAssocNames(aq.codingSchemeName));

    // Create statements to navigate both directions (up & down the
    // contextual chain).
    PreparedStatement getRelationship_1 = sqlConnection_.prepareStatement(new StringBuffer(
            "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", "
                    + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ")
                            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
                            .append(" WHERE " + stc_.sourceEntityCodeOrId + " = ? AND "
                                    + stc_.targetEntityCodeOrId + " = ? AND ")
                            .append(stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId
                                    + " IN (")
                            .append(assocParam).append(")").toString());

    PreparedStatement getRelationship_2 = sqlConnection_.prepareStatement(new StringBuffer(
            "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", "
                    + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ")
                            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
                            .append(" WHERE " + stc_.targetEntityCodeOrId + " = ? AND "
                                    + stc_.sourceEntityCodeOrId + " = ? AND ")
                            .append(stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId
                                    + " IN (")
                            .append(assocParam).append(")").toString());

    // Statement to update a multi-attributes key for an association
    // mapping.
    PreparedStatement updateMAK = sqlConnection_.prepareStatement(new StringBuffer("UPDATE ")
            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
            .append(" SET " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + " = ? " + " WHERE "
                    + stc_.codingSchemeNameOrId + " = ?")
            .append(" AND " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ?")
            .append(" AND " + stc_.entityCodeOrAssociationId + " = ?").toString());

    // Locate and qualify each affected association link with the context ID
    // ...
    try {
        PreparedStatement[] stmts = new PreparedStatement[] { getRelationship_1, getRelationship_2 };
        for (int s = 0; s < stmts.length; s++) {
            PreparedStatement stmt = stmts[s];
            for (int i = orderedPtrAUIToCode.size() - 1; i > 0; i--) {
                String code = (String) orderedPtrAUIToCode.getValue(i);
                String codePrev = (String) orderedPtrAUIToCode.getValue(i - 1);
                stmt.setString(1, code);
                stmt.setString(2, codePrev);
                stmt.setString(3, aq.codingSchemeName);

                ResultSet results = stmt.executeQuery();
                try {
                    // Iterate through all relevant association links ...
                    while (results.next()) {
                        String multiAttributesKey = results
                                .getString(SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY);
                        String targetConceptCode = results.getString(stc_.targetEntityCodeOrId);
                        String sourceConceptCode = results.getString(stc_.sourceEntityCodeOrId);
                        String association = results.getString(stc_.entityCodeOrAssociationId);

                        // If there is no key to correlate to the
                        // multi-attributes table,
                        // construct and add now.
                        if (multiAttributesKey == null) {
                            StringBuffer key = new StringBuffer().append(System.currentTimeMillis())
                                    .append((int) Math.floor((Math.random() * 100000))).append(totalCount);
                            multiAttributesKey = key.substring(0, Math.min(50, key.length()));
                            updateMAK.setString(1, multiAttributesKey);
                            updateMAK.setString(2, aq.codingSchemeName);
                            updateMAK.setString(3, sourceConceptCode);
                            updateMAK.setString(4, targetConceptCode);
                            updateMAK.setString(5, association);
                            updateMAK.execute();
                        }

                        // Add a context qualifier to the multi-attributes
                        // table.
                        try {
                            addEntityAssociationQualifierToEntityAssociation(aq.codingSchemeName,
                                    multiAttributesKey, aq.qualifierName, hcd);
                            contextLinks++;
                        } catch (SQLException e) {
                            // Because we qualify all relationships along
                            // the PTR and
                            // the HCD is identical for siblings at the same
                            // PTR some
                            // exceptions with regards to identical keys
                            // will come up.

                            // We try to bypass altogether if the message
                            // indicates duplication.
                            // However, message text can vary based on the
                            // database engine.
                            // Rather than exit in error, log the message
                            // and continue.
                            if (!e.getMessage().contains("Duplicate")) {
                                messages_.warn("Unable to add context qualifier to association.", e);
                            }
                        }
                    }
                } finally {
                    results.close();
                }
            }
        }
    } finally {
        updateMAK.close();
        getRelationship_1.close();
        getRelationship_2.close();
    }
    return contextLinks;
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UmlsCommon.UMLSBaseCode.java

/**
 * Adds qualification to concepts and associations in the LexGrid
 * repository./* ww w.  java  2  s  . c  om*/
 * 
 * @param aq
 *            Qualification information from the UMLS source.
 * @param constructHCD
 *            Indicates whether artificial context values should be
 *            constructed if not provided in the UMLS information.
 * @param rela
 *            The relationship attribute defined by UMLS (can be empty or
 *            null).
 * @param totalCount
 *            The total number of context links qualified previously.
 * @return The number of contextual links qualified in the repository for
 *         the given UMLS info.
 * @throws SQLException
 */
protected int loadContext(AssociationQualification aq, boolean constructHCD, String rela, int totalCount)
        throws SQLException {
    // If a context identifier was assigned, use it.
    // If a context identifier is not assigned and the option to construct
    // is enabled,
    // derive one based on the root concept code and path to root AUI
    // values.
    int contextLinks = 0;
    String hcd = aq.qualifierValue;
    if (constructHCD && StringUtils.isBlank(hcd) && StringUtils.isNotBlank(aq.pathToRoot)
            && StringUtils.isNotBlank(aq.sourceConceptCode)) {
        MessageDigest md = getSHA1();
        md.reset();
        md.update(aq.pathToRoot.getBytes());
        hcd = String.valueOf(md.digest(aq.sourceConceptCode.getBytes()));
    }
    if (StringUtils.isBlank(hcd))
        return 0;

    // Iterate through the path to root and determine the codes for
    // participating AUIs. We maintain a LRU cache of AUIs to codes to
    // assist.
    // If the associated code is not in the cache, find and cache it here.
    ListOrderedMap orderedPtrAUIToCode = new ListOrderedMap();

    // Break up the path to root into AUIs ...
    String[] auis = aq.pathToRoot.split("\\.");
    if (auis.length > 0) {
        // Check the cache for each. If not found, perform and cache the
        // AUI to code mapping.
        PreparedStatement getPTRCode = umlsConnection2_
                .prepareStatement("SELECT CODE FROM MRCONSO WHERE AUI = ?");
        try {
            String nextCode, nextAUI;
            for (int i = 0; i < auis.length; i++) {
                // Check for registered code in the cache.
                nextAUI = auis[i];
                nextCode = (String) auiToCodeCache_.get(nextAUI);

                // If not cached, perform lookup ...
                if (nextCode == null) {
                    getPTRCode.setString(1, nextAUI);
                    ResultSet ptrCodes = getPTRCode.executeQuery();
                    int count = 0;
                    try {
                        while (ptrCodes.next()) {
                            count++;
                            nextCode = ptrCodes.getString(1);
                        }
                    } finally {
                        ptrCodes.close();
                    }
                    // If one to one mapping (probably should always be, but
                    // doesn't
                    // hurt to check), add to the cache for quick lookup
                    // later...
                    if (count == 1)
                        auiToCodeCache_.put(nextAUI, nextCode);
                }

                // Was it resolved?
                if (nextCode != null)
                    orderedPtrAUIToCode.put(nextAUI, nextCode);
            }
        } finally {
            getPTRCode.close();
        }
    }
    // Ensure we have included the original AUI to code mapping from the
    // provided UMLS qualification info; inserted last as the root
    // of the path.
    orderedPtrAUIToCode.put(aq.sourceConceptAUI, aq.sourceConceptCode);

    // /////////////////////////////////////////////////////////////////////
    // We have all the participating codes and AUIs.
    // Add context qualifiers to the text presentation of each concept
    // based on code/AUI pairs.
    // /////////////////////////////////////////////////////////////////////
    for (OrderedMapIterator omi = orderedPtrAUIToCode.orderedMapIterator(); omi.hasNext();) {
        omi.next();
        String aui = (String) omi.getKey();
        String code = (String) omi.getValue();
        if (code != null)
            qualifyConceptPresentation(code, aui, aq.codingSchemeName, aq.qualifierName, hcd);
    }

    // /////////////////////////////////////////////////////////////////////
    // At this point we have taken care of all the concept qualifiers.
    // Now find and similarly tag each participating association link
    // between AUIs in the path to root chain.
    // /////////////////////////////////////////////////////////////////////

    // Statements to find LexGrid association to concept mappings.
    // Check source to target (parent association as processed)
    // or target to source (child association as processed).

    // Honor the association specified in the MRHIER entry, if provided.
    // For example, the UMLS 'inverse_isa' is mapped on load to 'hasSubtype'
    // association name; account for that here.
    String assoc = mapRela(rela);

    // If a specific relation attribute (rela) was not provided, consider
    // all relevant
    // hierarchical associations (including UMLS standard or source-specific
    // names).
    String assocParam = StringUtils.isNotBlank(assoc) ? '\'' + assoc + '\''
            : toCommaDelimitedWithQuotes(getHierAssocNames(aq.codingSchemeName));

    // Create statements to navigate both directions (up & down the
    // contextual chain).
    PreparedStatement getRelationship_1 = sqlConnection_.prepareStatement(new StringBuffer(
            "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", "
                    + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ")
                            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
                            .append(" WHERE " + stc_.sourceEntityCodeOrId + " = ? AND "
                                    + stc_.targetEntityCodeOrId + " = ? AND")
                            .append(" " + stc_.codingSchemeNameOrId + " = ? AND "
                                    + stc_.entityCodeOrAssociationId + " IN (")
                            .append(assocParam).append(")").toString());

    PreparedStatement getRelationship_2 = sqlConnection_.prepareStatement(new StringBuffer(
            "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", "
                    + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ")
                            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
                            .append(" WHERE " + stc_.targetEntityCodeOrId + " = ? AND "
                                    + stc_.sourceEntityCodeOrId + " = ? AND")
                            .append(" " + stc_.codingSchemeNameOrId + " = ? AND "
                                    + stc_.entityCodeOrAssociationId + " IN (")
                            .append(assocParam).append(")").toString());

    // Statement to update a multi-attributes key for an association
    // mapping.
    PreparedStatement updateMAK = sqlConnection_.prepareStatement(new StringBuffer("UPDATE ")
            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
            .append(" SET " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + " = ? " + " WHERE "
                    + stc_.codingSchemeNameOrId + " = ?")
            .append(" AND " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ?")
            .append(" AND " + stc_.entityCodeOrAssociationId + " = ?").toString());

    // Locate and qualify each affected association link with the context ID
    // ...
    try {
        PreparedStatement[] stmts = new PreparedStatement[] { getRelationship_1, getRelationship_2 };
        for (int s = 0; s < stmts.length; s++) {
            PreparedStatement stmt = stmts[s];
            for (int i = orderedPtrAUIToCode.size() - 1; i > 0; i--) {
                String code = (String) orderedPtrAUIToCode.getValue(i);
                String codePrev = (String) orderedPtrAUIToCode.getValue(i - 1);
                stmt.setString(1, code);
                stmt.setString(2, codePrev);
                stmt.setString(3, aq.codingSchemeName);

                ResultSet results = stmt.executeQuery();
                try {
                    // Iterate through all relevant association links ...
                    while (results.next()) {
                        String multiAttributesKey = results
                                .getString(SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY);
                        String targetConceptCode = results.getString(stc_.targetEntityCodeOrId);
                        String sourceConceptCode = results.getString(stc_.sourceEntityCodeOrId);
                        String association = results.getString(stc_.entityCodeOrAssociationId);

                        // If there is no key to correlate to the
                        // multi-attributes table,
                        // construct and add now.
                        if (multiAttributesKey == null) {
                            StringBuffer key = new StringBuffer().append(System.currentTimeMillis())
                                    .append((int) Math.floor((Math.random() * 100000))).append(totalCount);
                            multiAttributesKey = key.substring(0, Math.min(50, key.length()));
                            updateMAK.setString(1, multiAttributesKey);
                            updateMAK.setString(2, aq.codingSchemeName);
                            updateMAK.setString(3, sourceConceptCode);
                            updateMAK.setString(4, targetConceptCode);
                            updateMAK.setString(5, association);
                            updateMAK.execute();
                        }

                        // Add a context qualifier to the multi-attributes
                        // table.
                        try {
                            addEntityAssociationQualifierToEntityAssociation(aq.codingSchemeName,
                                    multiAttributesKey, aq.qualifierName, hcd);
                            contextLinks++;
                        } catch (SQLException e) {
                            // Because we qualify all relationships along
                            // the PTR and
                            // the HCD is identical for siblings at the same
                            // PTR some
                            // exceptions with regards to identical keys
                            // will come up.

                            // We try to bypass altogether if the message
                            // indicates duplication.
                            // However, message text can vary based on the
                            // database engine.
                            // Rather than exit in error, log the message
                            // and continue.
                            if (!e.getMessage().contains("Duplicate")) {
                                messages_.warn("Unable to add context qualifier to association.", e);
                            }
                        }
                    }
                } finally {
                    results.close();
                }
            }
        }
    } finally {
        updateMAK.close();
        getRelationship_1.close();
        getRelationship_2.close();
    }
    return contextLinks;
}

From source file:org.cesecore.config.ExtendedKeyUsageConfiguration.java

/**
 * Fill the map and list with OIDs from the configuration file
 *///from  ww  w  .  ja v  a2  s  . c  o  m
@SuppressWarnings("unchecked")
private static synchronized void fillExtendedKeyUsageOidsAndTexts() {
    final ListOrderedMap map = new ListOrderedMap();
    final Configuration conf = ConfigurationHolder.instance();
    final String ekuname = "extendedkeyusage.name.";
    final String ekuoid = "extendedkeyusage.oid.";
    for (int i = 0; i < 255; i++) {
        final String oid = conf.getString(ekuoid + i);
        if (oid != null) {
            String name = conf.getString(ekuname + i);
            if (name != null) {
                // A null value in the properties file means that we should not use this value, so set it to null for real
                if (name.equalsIgnoreCase("null")) {
                    name = null;
                } else {
                    map.put(oid, name);
                }
            } else {
                log.error("Found extended key usage oid " + oid
                        + ", but no name defined. Not adding to list of extended key usages.");
            }
        }
        // No eku with a certain number == continue trying next, we will try 0-255.
    }
    log.debug("Read " + map.size() + " extended key usages.");
    extendedKeyUsageOids = map.asList();
    if ((extendedKeyUsageOids == null) || (extendedKeyUsageOids.size() == 0)) {
        log.error(
                "Extended key usage OIDs is null or zero length, there is a serious error with extendedkeyusage.properties");
        extendedKeyUsageOids = new ArrayList<String>();
    }
    extendedKeyUsageOidsAndNames = Collections.synchronizedMap(map);
}

From source file:org.esupportail.portlet.filemanager.portlet.PortletController.java

@RequestMapping(value = { "VIEW" }, params = { "action=browseMobile" })
public ModelAndView browseMobile(RenderRequest request, RenderResponse response, @RequestParam String dir) {
    this.init(request);

    String decodedDir = pathEncodingUtils.decodeDir(dir);

    ModelMap model;//from  w  w w  .j  a  va 2  s.c o  m
    if (!(dir == null || dir.length() == 0 || decodedDir.equals(JsTreeFile.ROOT_DRIVE))) {
        if (this.serverAccess.formAuthenticationRequired(decodedDir, userParameters)) {
            ListOrderedMap parentPathes = pathEncodingUtils.getParentsEncPathes(decodedDir, null, null);
            // we want to get the (last-1) key of sortedmap "parentPathes"
            String parentDir = (String) parentPathes.get(parentPathes.size() - 2);
            model = new ModelMap("currentDir", dir);
            model.put("parentDir", parentDir);
            model.put("username", this.serverAccess.getUserPassword(decodedDir, userParameters).getUsername());
            model.put("password", this.serverAccess.getUserPassword(decodedDir, userParameters).getPassword());
            return new ModelAndView("authenticationForm-portlet-mobile", model);
        }
    }
    model = browse(dir);
    return new ModelAndView("view-portlet-mobile", model);
}

From source file:org.esupportail.portlet.filemanager.portlet.PortletController.java

@RequestMapping(value = { "VIEW" }, params = { "action=browseWai" })
public ModelAndView browseWai(RenderRequest request, RenderResponse response,
        @RequestParam(required = false) String dir, @RequestParam(required = false) String msg) {
    this.init(request);

    String decodedDir = pathEncodingUtils.decodeDir(dir);

    if (!serverAccess.isInitialized(userParameters)) {
        serverAccess.initializeServices(userParameters);
    }//from   w  w  w .ja  va 2s. com

    ModelMap model;
    if (!(dir == null || dir.length() == 0 || decodedDir.equals(JsTreeFile.ROOT_DRIVE))) {
        if (this.serverAccess.formAuthenticationRequired(decodedDir, userParameters)) {
            ListOrderedMap parentPathes = pathEncodingUtils.getParentsEncPathes(decodedDir, null, null);
            // we want to get the (last-1) key of sortedmap "parentPathes"
            String parentDir = (String) parentPathes.get(parentPathes.size() - 2);
            model = new ModelMap("currentDir", dir);
            model.put("parentDir", parentDir);
            model.put("username", this.serverAccess.getUserPassword(decodedDir, userParameters).getUsername());
            model.put("password", this.serverAccess.getUserPassword(decodedDir, userParameters).getPassword());
            if (msg != null)
                model.put("msg", msg);
            return new ModelAndView("authenticationForm-portlet-wai", model);
        }
    }

    model = browse(dir);
    FormCommand command = new FormCommand();
    model.put("command", command);
    if (msg != null)
        model.put("msg", msg);
    return new ModelAndView("view-portlet-wai", model);
}

From source file:org.etk.entity.engine.plugins.transaction.TransactionUtil.java

/**
 * Remove the stamp from stack (when resuming)
 */// w w  w .jav a 2s .  com
private static void popTransactionStartStamp() {
    ListOrderedMap map = (ListOrderedMap) suspendedTxStartStamps.get();
    if (map.size() > 0) {
        transactionStartStamp.set((Timestamp) map.remove(map.lastKey()));
    } else {
        logger.debug("Error in transaction handling - no saved start stamp found - using NOW.");
        transactionStartStamp.set(UtilDateTime.nowTimestamp());
    }
}

From source file:org.jahia.services.content.ConflictResolver.java

private Map<String, String> getOrdering(ListOrderedMap uuids1, List<String> removed) {
    Map<String, String> previousMap = new LinkedHashMap<String, String>();
    ListIterator<?> it = uuids1.keyList().listIterator(uuids1.size());
    String previous = "";
    while (it.hasPrevious()) {
        String uuid = (String) it.previous();
        if (!removed.contains(uuid)) {
            previousMap.put(uuid, previous);
            previous = uuid;//w w  w. ja  v a 2 s. c om
        }
    }
    return previousMap;
}

From source file:org.noerp.entity.transaction.TransactionUtil.java

/**
* Remove the stamp from stack (when resuming)
*///ww  w.ja v  a2s .  c o m
private static void popTransactionStartStamp() {
    ListOrderedMap map = (ListOrderedMap) suspendedTxStartStamps.get();
    if (map.size() > 0) {
        transactionStartStamp.set((Timestamp) map.remove(map.lastKey()));
    } else {
        Debug.logError("Error in transaction handling - no saved start stamp found - using NOW.", module);
        transactionStartStamp.set(UtilDateTime.nowTimestamp());
    }
}