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

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

Introduction

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

Prototype

public Object put(Object key, Object value) 

Source Link

Usage

From source file:cn.fql.utility.CollectionUtility.java

/**
 * Sort collection with order, each group is a arraylist
 *
 * @param source source list/*from   www .ja  v a 2s. co  m*/
 * @param key    specified key which is used to be compared
 * @return <code>MapListAdapter</code>
 */
public static ListOrderedMap sortCollectionWithOrder(List source, Object key) {
    ListOrderedMap lstOrderedMap = new ListOrderedMap();
    for (Iterator it = source.iterator(); it.hasNext();) {
        Map rowMap = (Map) it.next();
        Object keyValue = rowMap.get(key);
        List groupList = (List) lstOrderedMap.get(keyValue);
        if (groupList == null) {
            groupList = new ArrayList();
            lstOrderedMap.put(keyValue, groupList);
        }
        groupList.add(rowMap);
    }
    return lstOrderedMap;
}

From source file:models.SkillTag.java

public static ListOrderedMap getCategoryTagMap() {
    ListOrderedMap ctmap = new ListOrderedMap();
    List<SkillTag> list = JPA.em().createQuery("from SkillTag s where s.tagType=:tagType  order by s.seq asc")
            .setParameter("tagType", SkillTag.TagType.CATEGORY).setMaxResults(150).getResultList();
    for (SkillTag st : list) {
        ctmap.put(st.id, st.tagName);
    }//from  w w  w .j a va 2s.  com
    return ctmap;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.EntityRetryController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;/*from   w  w w.  j av  a 2 s .c o  m*/
    }

    VitroRequest vreq = new VitroRequest(request);
    String siteAdminUrl = vreq.getContextPath() + Controllers.SITE_ADMIN;

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    epo.setBeanClass(Individual.class);
    epo.setImplementationClass(IndividualImpl.class);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    LoginStatusBean loginBean = LoginStatusBean.getBean(request);
    WebappDaoFactory myWebappDaoFactory = getWebappDaoFactory(loginBean.getUserURI());

    IndividualDao ewDao = myWebappDaoFactory.getIndividualDao();
    epo.setDataAccessObject(ewDao);
    VClassDao vcDao = myWebappDaoFactory.getVClassDao();
    VClassGroupDao cgDao = myWebappDaoFactory.getVClassGroupDao();
    DataPropertyDao dpDao = myWebappDaoFactory.getDataPropertyDao();

    Individual individualForEditing = null;
    if (epo.getUseRecycledBean()) {
        individualForEditing = (Individual) epo.getNewBean();
    } else {
        String uri = vreq.getParameter("uri");
        if (uri != null) {
            try {
                individualForEditing = (Individual) ewDao.getIndividualByURI(uri);
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
            }
        } else {
            individualForEditing = new IndividualImpl();
            if (vreq.getParameter("VClassURI") != null) {
                individualForEditing.setVClassURI(vreq.getParameter("VClassURI"));
            }
        }

        epo.setOriginalBean(individualForEditing);

        //make a simple mask for the entity's id
        Object[] simpleMaskPair = new Object[2];
        simpleMaskPair[0] = "URI";
        simpleMaskPair[1] = individualForEditing.getURI();
        epo.getSimpleMask().add(simpleMaskPair);

    }

    //set any validators

    LinkedList lnList = new LinkedList();
    lnList.add(new RequiredFieldValidator());
    epo.getValidatorMap().put("Name", lnList);

    //make a postinsert pageforwarder that will send us to a new entity's fetch screen
    epo.setPostInsertPageForwarder(new EntityInsertPageForwarder());
    epo.setPostDeletePageForwarder(new UrlForwarder(siteAdminUrl));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(ewDao.getClass().getDeclaredMethod("getIndividualByURI", args));
    } catch (NoSuchMethodException e) {
        log.error("EntityRetryController could not find the entityByURI method in the dao");
    }

    epo.setIdFieldName("URI");
    epo.setIdFieldClass(String.class);

    HashMap hash = new HashMap();

    if (individualForEditing.getVClassURI() == null) {
        // we need to do a special thing here to make an option list with option groups for the classgroups.
        List classGroups = cgDao.getPublicGroupsWithVClasses(true, true, false); // order by displayRank, include uninstantiated classes, don't get the counts of individuals
        Iterator classGroupIt = classGroups.iterator();
        ListOrderedMap optGroupMap = new ListOrderedMap();
        while (classGroupIt.hasNext()) {
            VClassGroup group = (VClassGroup) classGroupIt.next();
            List classes = group.getVitroClassList();
            optGroupMap.put(group.getPublicName(), FormUtils.makeOptionListFromBeans(classes, "URI", "Name",
                    individualForEditing.getVClassURI(), null, false));
        }
        hash.put("VClassURI", optGroupMap);
    } else {
        VClass vClass = null;
        Option opt = null;
        try {
            vClass = vcDao.getVClassByURI(individualForEditing.getVClassURI());
        } catch (Exception e) {
        }
        if (vClass != null) {
            opt = new Option(vClass.getURI(), vClass.getName(), true);
        } else {
            opt = new Option(individualForEditing.getVClassURI(), individualForEditing.getVClassURI(), true);
        }
        List<Option> optList = new LinkedList<Option>();
        optList.add(opt);
        hash.put("VClassURI", optList);
    }

    hash.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getDisplayOptionsList(individualForEditing));
    hash.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getUpdateOptionsList(individualForEditing));
    hash.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getPublishOptionsList(individualForEditing));

    FormObject foo = new FormObject();
    foo.setOptionLists(hash);

    ListOrderedMap dpMap = new ListOrderedMap();

    //make dynamic datatype property fields
    List<VClass> vclasses = individualForEditing.getVClasses(true);
    if (vclasses == null) {
        vclasses = new ArrayList<VClass>();
        if (individualForEditing.getVClassURI() != null) {
            try {
                VClass cls = vreq.getUnfilteredWebappDaoFactory().getVClassDao()
                        .getVClassByURI(individualForEditing.getVClassURI());
                if (cls != null) {
                    vclasses.add(cls);
                }
            } catch (Exception e) {
            }
        }
    }
    List<DataProperty> allApplicableDataprops = new ArrayList<DataProperty>();
    for (VClass cls : vclasses) {
        List<DataProperty> dataprops = dpDao.getDataPropertiesForVClass(cls.getURI());
        for (DataProperty dp : dataprops) {
            boolean notDuplicate = true;
            for (DataProperty existingDp : allApplicableDataprops) {
                if (existingDp.getURI().equals(dp.getURI())) {
                    notDuplicate = false;
                    break;
                }
            }
            if (notDuplicate) {
                allApplicableDataprops.add(dp);
            }
        }
    }
    Collections.sort(allApplicableDataprops);

    if (allApplicableDataprops != null) {
        Iterator<DataProperty> datapropsIt = allApplicableDataprops.iterator();

        while (datapropsIt.hasNext()) {
            DataProperty d = datapropsIt.next();
            if (!dpMap.containsKey(d.getURI())) {
                dpMap.put(d.getURI(), d);
            }

        }

        if (individualForEditing.getDataPropertyList() != null) {
            Iterator<DataProperty> existingDps = individualForEditing.getDataPropertyList().iterator();
            while (existingDps.hasNext()) {
                DataProperty existingDp = existingDps.next();
                // Since the edit form begins with a "name" field, which gets saved as the rdfs:label,
                // do not want to include the label as well. 
                if (!existingDp.getPublicName().equals("label")) {
                    dpMap.put(existingDp.getURI(), existingDp);
                }
            }
        }

        List<DynamicField> dynamicFields = new ArrayList();
        Iterator<String> dpHashIt = dpMap.orderedMapIterator();
        while (dpHashIt.hasNext()) {
            String uri = dpHashIt.next();
            DataProperty dp = (DataProperty) dpMap.get(uri);
            DynamicField dynamo = new DynamicField();
            dynamo.setName(dp.getPublicName());
            dynamo.setTable("DataPropertyStatement");
            dynamo.setVisible(dp.getDisplayLimit());
            dynamo.setDeleteable(true);
            DynamicFieldRow rowTemplate = new DynamicFieldRow();
            Map parameterMap = new HashMap();
            parameterMap.put("DatatypePropertyURI", dp.getURI());
            rowTemplate.setParameterMap(parameterMap);
            dynamo.setRowTemplate(rowTemplate);
            try {
                Iterator<DataPropertyStatement> existingValues = dp.getDataPropertyStatements().iterator();
                while (existingValues.hasNext()) {
                    DataPropertyStatement existingValue = existingValues.next();
                    DynamicFieldRow row = new DynamicFieldRow();
                    //TODO: UGH
                    //row.setId(existingValue.getId());
                    row.setParameterMap(parameterMap);
                    row.setValue(existingValue.getData());
                    if (dynamo.getRowList() == null)
                        dynamo.setRowList(new ArrayList());
                    dynamo.getRowList().add(row);
                }
            } catch (NullPointerException npe) {
                //whatever
            }
            if (dynamo.getRowList() == null)
                dynamo.setRowList(new ArrayList());
            dynamo.getRowList().add(rowTemplate);
            dynamicFields.add(dynamo);
        }
        foo.setDynamicFields(dynamicFields);
    }

    foo.setErrorMap(epo.getErrMsgMap());

    epo.setFormObject(foo);

    // DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    DateFormat minutesOnlyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    DateFormat dateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd");
    FormUtils.populateFormFromBean(individualForEditing, action, epo, foo, epo.getBadValueMap());

    List cList = new ArrayList();
    cList.add(new IndividualDataPropertyStatementProcessor());
    //cList.add(new SearchReindexer()); // handled for now by SearchReindexingListener on model
    epo.setChangeListenerList(cList);

    epo.getAdditionalDaoMap().put("DataPropertyStatement", myWebappDaoFactory.getDataPropertyStatementDao()); // EntityDatapropProcessor will look for this
    epo.getAdditionalDaoMap().put("DataProperty", myWebappDaoFactory.getDataPropertyDao()); // EntityDatapropProcessor will look for this

    ApplicationBean appBean = vreq.getAppBean();

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/entity_retry.jsp");
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("title", "Individual Editing Form");
    request.setAttribute("css",
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + appBean.getThemeDir() + "css/edit.css\"/>");
    request.setAttribute("scripts", "/js/edit/entityRetry.js");
    // NC Commenting this out for now. Going to pass on DWR for moniker and use jQuery instead
    // request.setAttribute("bodyAttr"," onLoad=\"monikerInit()\"");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "Individual");
    setRequestAttributes(request, epo);
    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("EntityRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:com.doculibre.constellio.spellchecker.SpellChecker.java

private void addSuggestions(String sentence, String collectionName, ListOrderedMap orderedMap,
        NamedList<Object> namedList, Locale locale) {
    if (sentence.length() > 250) {
        throw new IllegalArgumentException("String is too long, rejected by spell checker");
    }/*w  ww  .  ja v  a  2 s.  c  o  m*/

    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection collection = collectionServices.get(collectionName);
    if (collection != null && collection.isSpellCheckerActive()) {
        String spellCheckerLanguage;
        if (locale != null) {
            spellCheckerLanguage = locale.getLanguage();
        } else {
            spellCheckerLanguage = collection.getSpellCheckerLanguage();
        }
        DICTIONARIES dictionary;
        if (Locale.ENGLISH.getLanguage().equals(spellCheckerLanguage)) {
            dictionary = DICTIONARIES.en_US;
        } else if ("es".equals(spellCheckerLanguage)) {
            dictionary = DICTIONARIES.es_MX;
        } else {
            dictionary = DICTIONARIES.fr_FR;
        }

        Hunspell.Dictionary hunspellDictionary = this.dictionariesMap.get(dictionary);
        String[] words = sentence.split(" ");
        if (words.length > 0) {
            for (int i = 0; i < words.length; i++) {
                String currentWord = words[i];
                currentWord = StringUtils.remove(currentWord, '(');
                currentWord = StringUtils.remove(currentWord, ')');
                String currentWordWOAccent = AsciiUtils.convertNonAscii(currentWord);
                if (hunspellDictionary.misspelled(currentWord)) {
                    List<String> suggestionsForWord = hunspellDictionary.suggest(currentWord);
                    if (suggestionsForWord.size() > 0) {
                        boolean ignoreSuggestionForWord = false;
                        for (String suggestionForWord : suggestionsForWord) {
                            String sugWOAccent = AsciiUtils.convertNonAscii(suggestionForWord);
                            if (currentWordWOAccent.toLowerCase().equals(sugWOAccent.toLowerCase())) {
                                ignoreSuggestionForWord = true;
                            }
                        }
                        if (orderedMap != null) {
                            orderedMap.put(currentWord, ignoreSuggestionForWord ? null : suggestionsForWord);
                        } else {
                            addNamedList(namedList, currentWord, !ignoreSuggestionForWord,
                                    ignoreSuggestionForWord ? null : suggestionsForWord);
                        }
                    }
                } else {
                    if (orderedMap != null) {
                        orderedMap.put(currentWord, null);
                    } else {
                        addNamedList(namedList, currentWord, false, null);
                    }
                }
            }
        }
    }
}

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

/**
 * Adds qualification to concepts and associations in the LexGrid
 * repository.//ww w  .  j  a v  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./*from   ww w .ja  va2  s.  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 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.anyframe.hibernate.datatype.HibernateBlobTest.java

/**
 * File information is set for Blob Data Type. 
 * /* www  .j av  a2  s  . c om*/
 * @param isUpdate
 *            update It is checked the file is for update.
 * @return ListOrderedMap Map included file information
 */
protected ListOrderedMap getFileInfo(boolean isUpdate) {
    ListOrderedMap fileMap = new ListOrderedMap();
    File file;
    if (!isUpdate) {
        file = new File("./testdata/LobTestData.txt");
    } else {
        file = new File("./testdata/LobUpdateTestData.txt");
    }
    if (file.exists()) {
        FileInputStream fis = null;
        byte[] fileContent = null;
        try {
            fis = new FileInputStream(file);
            fileContent = FileCopyUtils.copyToByteArray(fis);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail("fail to read file");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        fileMap.put("fileName", file.getName());
        fileMap.put("fileSize", new java.math.BigDecimal(new Long(file.length()).doubleValue()));
        fileMap.put("fileContentByte", fileContent);

        System.out.println(" lobHelper : " + session.getLobHelper());
        try {
            fileMap.put("fileContentBlob", session.getLobHelper().createBlob(fileContent));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("fail to convert ByteArray into Blob");
        }
    } else {
        Assert.fail("the file doesn't exist");
    }
    return fileMap;
}

From source file:org.apache.ddlutils.io.DatabaseDataIO.java

/**
 * Sorts the given table according to their foreign key order.
 * //from www .  j  a  va2  s .c  om
 * @param tables The tables
 * @return The sorted tables
 */
private List sortTables(Table[] tables) {
    ArrayList result = new ArrayList();
    HashSet processed = new HashSet();
    ListOrderedMap pending = new ListOrderedMap();

    for (int idx = 0; idx < tables.length; idx++) {
        Table table = tables[idx];

        if (table.getForeignKeyCount() == 0) {
            result.add(table);
            processed.add(table);
        } else {
            HashSet waitedFor = new HashSet();

            for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++) {
                Table waitedForTable = table.getForeignKey(fkIdx).getForeignTable();

                if (!table.equals(waitedForTable)) {
                    waitedFor.add(waitedForTable);
                }
            }
            pending.put(table, waitedFor);
        }
    }

    HashSet newProcessed = new HashSet();

    while (!processed.isEmpty() && !pending.isEmpty()) {
        newProcessed.clear();
        for (Iterator it = pending.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            Table table = (Table) entry.getKey();
            HashSet waitedFor = (HashSet) entry.getValue();

            waitedFor.removeAll(processed);
            if (waitedFor.isEmpty()) {
                it.remove();
                result.add(table);
                newProcessed.add(table);
            }
        }
        processed.clear();

        HashSet tmp = processed;

        processed = newProcessed;
        newProcessed = tmp;
    }
    // the remaining are within circular dependencies
    for (Iterator it = pending.keySet().iterator(); it.hasNext();) {
        result.add(it.next());
    }
    return result;
}

From source file:org.apache.ddlutils.platform.SqlBuilder.java

/**
 * Writes a statement that copies the data from the source to the target table. Note
 * that this copies only those columns that are in both tables.
 * Database-specific implementations might redefine this method though it usually
 * suffices to redefine the {@link #writeCastExpression(Column, Column)} method.
 * /*from  w  w w . j a  v  a  2 s. co  m*/
 * @param sourceTable The source table
 * @param targetTable The target table
 */
protected void copyData(Table sourceTable, Table targetTable) throws IOException {
    ListOrderedMap columns = new ListOrderedMap();

    for (int idx = 0; idx < sourceTable.getColumnCount(); idx++) {
        Column sourceColumn = sourceTable.getColumn(idx);
        Column targetColumn = targetTable.findColumn(sourceColumn.getName(),
                getPlatform().isDelimitedIdentifierModeOn());

        if (targetColumn != null) {
            columns.put(sourceColumn, targetColumn);
        }
    }

    print("INSERT INTO ");
    printIdentifier(getTableName(targetTable));
    print(" (");
    for (Iterator columnIt = columns.keySet().iterator(); columnIt.hasNext();) {
        printIdentifier(getColumnName((Column) columnIt.next()));
        if (columnIt.hasNext()) {
            print(",");
        }
    }
    print(") SELECT ");
    for (Iterator columnsIt = columns.entrySet().iterator(); columnsIt.hasNext();) {
        Map.Entry entry = (Map.Entry) columnsIt.next();

        writeCastExpression((Column) entry.getKey(), (Column) entry.getValue());
        if (columnsIt.hasNext()) {
            print(",");
        }
    }
    print(" FROM ");
    printIdentifier(getTableName(sourceTable));
    printEndOfStatement();
}

From source file:org.castafiore.designer.config.ui.EXStyleConfigForm.java

private Map<String, String> getProperties(int type) {
    String sType = TYPES[type];//www. j a v a2 s . c o  m

    ListOrderedMap result = new ListOrderedMap();
    Iterator<Object> iters = props.keySet().iterator();
    List<String> keys = new ArrayList<String>();

    while (iters.hasNext()) {
        Object next = iters.next();
        keys.add(next.toString());

    }

    Collections.sort(keys);

    for (String next : keys) {
        if (next.startsWith(sType + ".")) {
            result.put(next, props.get(next).toString());
        }
    }

    //Collections.sort(result.keyList());
    return result;
}