Example usage for java.util Hashtable size

List of usage examples for java.util Hashtable size

Introduction

In this page you can find the example usage for java.util Hashtable size.

Prototype

public synchronized int size() 

Source Link

Document

Returns the number of keys in this hashtable.

Usage

From source file:org.lexevs.system.ResourceManager.java

public String getInternalVersionStringForTag(String externalCodeSystemName, String tag)
        throws LBParameterException {
    if (externalCodeSystemName == null || externalCodeSystemName.length() == 0) {
        throw new LBParameterException("The parameter is required", SQLTableConstants.TBLCOL_CODINGSCHEMENAME);
    }/* www . j  av a 2 s. c  om*/

    // I'm going to cache this, because it is kind of expensive, and may be
    // a frequent operation
    String key = "internalVersionStringForTag:" + externalCodeSystemName + ":"
            + (tag == null || tag.length() == 0 ? KnownTags.PRODUCTION.toString() : tag);

    String version = (String) cache_.get(key);

    if (version != null) {
        return version;
    }

    // not in the cache, find it.

    Hashtable<String, String> temp = codingSchemeLocalNamesToInternalNameMap_.get(externalCodeSystemName);
    if (temp == null) {
        throw new LBParameterException("No coding scheme could be located for the values you provided",
                SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                externalCodeSystemName + ", " + tag);
    }

    // The hashtable that is returned is a mapping of versions to the
    // internal code system names.
    // it is likely but not guaranteed that all of the code system names
    // will be identical.
    // They should all map to the SAME urn however, so get the URN for the
    // first one.
    // ask the registry for the version number associated with the given tag
    // on the (found) urn.

    Enumeration<String> e = temp.elements();
    String urn = "";
    if (e.hasMoreElements()) {
        Set<String> uris = getAllURNsForInternalCodingSchemeName(e.nextElement());
        if (uris.size() == 1) {
            urn = uris.iterator().next();
        } else {
            if (uris.contains(externalCodeSystemName)) {
                for (String uri : uris) {
                    if (uri.equals(externalCodeSystemName)) {
                        urn = uri;
                    }
                }
            }
        }
    } else {
        throw new LBParameterException("No coding scheme could be located for the values you provided",
                SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                externalCodeSystemName + ", " + tag);
    }

    // if the tag is missing or null, then we should use "PRODUCTION"
    version = registry_.getVersionForTag(urn,
            (tag == null || tag.length() == 0 ? KnownTags.PRODUCTION.toString() : tag));

    if (version == null) {
        if (tag != null && !tag.equals(KnownTags.PRODUCTION.toString())) {
            // if they specified a tag, and it wasn't the production tag,
            // and we didn't find it
            // then the tag is invalid.
            throw new LBParameterException(
                    "No version of the code system " + externalCodeSystemName + " is tagged as " + tag);
        }
        // they didn't specify a tag, or the specified production, but
        // nothing it tagged
        // as production. If we only have one that matches, return it. Else,
        // ask for clairification.
        else if (temp.size() > 1) {

            throw new LBParameterException(
                    "Multiple code systems matched the values you provided - please be more specific (or designate one of the code systems as 'PRODUCTION'",
                    SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                    externalCodeSystemName + ", " + tag);
        } else {
            version = temp.keySet().toArray(new String[temp.size()])[0];
        }
    }

    cache_.put(key, version);
    return version;
}

From source file:org.LexGrid.LexBIG.Impl.dataAccess.SQLImplementedMethods.java

public static Entity buildCodedEntry(String internalCodingSchemeName, String internalVersionString, String code,
        String namespace, LocalNameList restrictToProperties, PropertyType[] restrictToPropertyTypes)
        throws UnexpectedInternalError, MissingResourceException {

    try {//from w w w .  j a v a 2 s.c o  m
        Entity concept = new Entity();
        concept.setEntityCode(code);

        SQLInterface si = ResourceManager.instance().getSQLInterface(internalCodingSchemeName,
                internalVersionString);

        //if the namespace is null (and its 2009 model), set it to the default (which is
        //equal to the codingSchemeName.
        //This shouldn't ever happen -- all classes that call this method should provide
        //a namespace.
        if (si.supports2009Model() && StringUtils.isBlank(namespace)) {
            namespace = internalCodingSchemeName;
        }

        ArrayList<Definition> definitions = new ArrayList<Definition>();
        ArrayList<Presentation> presentations = new ArrayList<Presentation>();
        ArrayList<Property> properties = new ArrayList<Property>();
        ArrayList<Comment> comments = new ArrayList<Comment>();

        ArrayList<PropertyLink> links = new ArrayList<PropertyLink>();

        PreparedStatement getEntityCode = null;
        PreparedStatement getEntityType = null;
        PreparedStatement getEntityProperties = null;
        PreparedStatement getPropertyLinks = null;

        try {
            StringBuffer buildEntity = new StringBuffer();

            buildEntity
                    .append("Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY) + " {AS} t1 ");

            if (si.supports2009Model()) {
                buildEntity.append("left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} t2 "
                        + "on t1." + SQLTableConstants.TBLCOL_ENTRYSTATEID + " = t2."
                        + SQLTableConstants.TBLCOL_ENTRYSTATEID);
            }

            buildEntity.append(" where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND "
                    + si.getSQLTableConstants().entityCodeOrId + " = ?");

            if (si.supports2009Model()) {
                buildEntity.append(" AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");
            }

            getEntityCode = si.modifyAndCheckOutPreparedStatement(buildEntity.toString());

            getEntityCode.setString(1, internalCodingSchemeName);
            getEntityCode.setString(2, code);
            if (si.supports2009Model()) {
                getEntityCode.setString(3, namespace);
            }

            ResultSet results = getEntityCode.executeQuery();

            // one and only one result
            if (results.next()) {
                concept.setIsDefined(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISDEFINED));
                concept.setIsAnonymous(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISANONYMOUS));
                concept.setIsActive(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISACTIVE));

                if (!si.supports2009Model()) {
                    concept.setStatus(results.getString(SQLTableConstants.TBLCOL_CONCEPTSTATUS));
                } else {
                    concept.setEntityCodeNamespace(namespace);
                }

                EntityDescription ed = new EntityDescription();
                ed.setContent(results.getString(SQLTableConstants.TBLCOL_ENTITYDESCRIPTION));
                concept.setEntityDescription(ed);

                if (si.supports2009Model()) {
                    String owner = results.getString(SQLTableConstants.TBLCOL_OWNER);
                    String status = results.getString(SQLTableConstants.TBLCOL_STATUS);
                    Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE);
                    Timestamp expirationDate = results.getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE);
                    String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID);
                    String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID);
                    String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE);
                    String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER);

                    EntryState es = new EntryState();

                    if (!StringUtils.isBlank(changeType)) {
                        es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType));
                    }
                    es.setContainingRevision(revisionId);
                    es.setPrevRevision(prevRevisionId);

                    es.setRelativeOrder(computeRelativeOrder(relativeOrder));

                    concept.setEntryState(es);

                    if (owner != null) {
                        concept.setOwner(owner);
                    }
                    concept.setStatus(status);
                    concept.setEffectiveDate(effectiveDate);
                    concept.setExpirationDate(expirationDate);
                }
            }

            results.close();
            si.checkInPreparedStatement(getEntityCode);

            if (si.supports2009Model()) {
                getEntityType = si.checkOutPreparedStatement(
                        "Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY_TYPE) + " where "
                                + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND "
                                + si.getSQLTableConstants().entityCodeOrId + " = ? AND "
                                + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");

                getEntityType.setString(1, internalCodingSchemeName);
                getEntityType.setString(2, code);
                getEntityType.setString(3, namespace);

                results = getEntityType.executeQuery();
                while (results.next()) {
                    concept.addEntityType(results.getString(SQLTableConstants.TBLCOL_ENTITYTYPE));
                }

                results.close();
                si.checkInPreparedStatement(getEntityType);
            } else {
                concept.addEntityType(SQLTableConstants.ENTITYTYPE_CONCEPT);
            }

            // populate the property links
            String addWhereSegment = (!si.supports2009Model()
                    ? (si.getSQLTableConstants().entityType + " = '" + SQLTableConstants.ENTITYTYPE_CONCEPT
                            + "' and ")
                    : "");

            getPropertyLinks = si
                    .checkOutPreparedStatement("Select " + SQLTableConstants.TBLCOL_SOURCEPROPERTYID + ", "
                            + SQLTableConstants.TBLCOL_LINK + ", " + SQLTableConstants.TBLCOL_TARGETPROPERTYID
                            + " from " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_LINKS) + " where "
                            + addWhereSegment + si.getSQLTableConstants().entityCodeOrEntityId + " = ? and "
                            + si.getSQLTableConstants().codingSchemeNameOrId + " = ?");
            getPropertyLinks.setString(1, code);
            getPropertyLinks.setString(2, internalCodingSchemeName);

            results = getPropertyLinks.executeQuery();

            while (results.next()) {
                String sourcePropertyId = results.getString(SQLTableConstants.TBLCOL_SOURCEPROPERTYID);
                String link = results.getString(SQLTableConstants.TBLCOL_LINK);
                String targetPropertyId = results.getString(SQLTableConstants.TBLCOL_TARGETPROPERTYID);

                PropertyLink pl = new PropertyLink();
                pl.setPropertyLink(link);
                pl.setSourceProperty(sourcePropertyId);
                pl.setTargetProperty(targetPropertyId);
                links.add(pl);
            }
            results.close();
            si.checkInPreparedStatement(getPropertyLinks);

            // codedEntry.setModVersion(null);

            StringBuffer propertyQuery = new StringBuffer();

            // I'm constructing a left join query to get the property
            // results I need from 3 (or 2 in 1.5 table version) different
            // tables at once, rather than doing a query on each.

            propertyQuery.append("SELECT a." + SQLTableConstants.TBLCOL_PROPERTYID + ", a."
                    + SQLTableConstants.TBLCOL_PROPERTYNAME + ", a." + SQLTableConstants.TBLCOL_LANGUAGE
                    + ", a." + SQLTableConstants.TBLCOL_FORMAT + ", a." + SQLTableConstants.TBLCOL_ISPREFERRED
                    + ", a." + SQLTableConstants.TBLCOL_DEGREEOFFIDELITY + ", a."
                    + SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT + ", a."
                    + SQLTableConstants.TBLCOL_REPRESENTATIONALFORM + ", a."
                    + SQLTableConstants.TBLCOL_PROPERTYVALUE + ", a." + SQLTableConstants.TBLCOL_PROPERTYTYPE
                    + (si.supports2009Model() ? (", a." + SQLTableConstants.TBLCOL_ENTRYSTATEID) : "")
                    + (si.supports2009Model() ? ", es.*" : "") + ", b." + SQLTableConstants.TBLCOL_TYPENAME
                    + ", b." + SQLTableConstants.TBLCOL_ATTRIBUTEVALUE + ", b." + SQLTableConstants.TBLCOL_VAL1
                    + ", b." + SQLTableConstants.TBLCOL_VAL2);

            propertyQuery.append(" FROM ");

            String codingSchemeName = si.getSQLTableConstants().codingSchemeNameOrId;
            String concptCode = si.getSQLTableConstants().entityCodeOrEntityId;

            propertyQuery.append(si.getTableName(SQLTableConstants.ENTITY_PROPERTY) + " {AS} a ");
            propertyQuery.append(
                    " left join " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES));
            propertyQuery.append(" {AS} b on a." + codingSchemeName + " = b." + codingSchemeName + " and a."
                    + concptCode + " = b." + concptCode + " and a." + SQLTableConstants.TBLCOL_PROPERTYID
                    + " = b." + SQLTableConstants.TBLCOL_PROPERTYID);

            if (si.supports2009Model()) {
                propertyQuery
                        .append(" left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} es ");
                propertyQuery.append("on a." + SQLTableConstants.TBLCOL_ENTRYSTATEID);
                propertyQuery.append(" = es." + SQLTableConstants.TBLCOL_ENTRYSTATEID);
            }

            propertyQuery.append(" where a." + concptCode + " = ? " + "and a." + codingSchemeName + " = ?");
            if (si.supports2009Model()) {
                propertyQuery.append(" and a." + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");
            }

            if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) {
                propertyQuery.append(" AND (");
                for (int i = 0; i < restrictToProperties.getEntryCount(); i++) {
                    propertyQuery.append("  " + si.getSQLTableConstants().propertyOrPropertyName + " = ? ");
                    if (i + 1 < restrictToProperties.getEntryCount()) {
                        propertyQuery.append(" OR ");
                    }
                }
                propertyQuery.append(")");

            }

            if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) {
                propertyQuery.append(" AND (");

                for (int i = 0; i < restrictToPropertyTypes.length; i++) {
                    propertyQuery.append(" " + SQLTableConstants.TBLCOL_PROPERTYTYPE + " = ? ");
                    if (i + 1 < restrictToPropertyTypes.length) {
                        propertyQuery.append(" OR ");
                    }
                }
                propertyQuery.append(")");

            }

            getEntityProperties = si.modifyAndCheckOutPreparedStatement(propertyQuery.toString());

            int i = 1;
            getEntityProperties.setString(i++, code);
            getEntityProperties.setString(i++, internalCodingSchemeName);
            if (si.supports2009Model()) {
                getEntityProperties.setString(i++, namespace);
            }

            if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) {
                for (int j = 0; j < restrictToProperties.getEntryCount(); j++) {
                    getEntityProperties.setString(i++, restrictToProperties.getEntry(j));
                }
            }
            if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) {
                for (int j = 0; j < restrictToPropertyTypes.length; j++) {
                    String pts = RestrictionImplementations.mapPropertyType(restrictToPropertyTypes[j]);
                    getEntityProperties.setString(i++, pts);
                }
            }

            results = getEntityProperties.executeQuery();

            // store the property from the last row
            org.LexGrid.commonTypes.Property newProperty = null;

            // all of the fields that come from the Property table
            String propertyType, property, propertyValue, language, presentationFormat, degreeOfFidelity,
                    propertyId, representationalForm;
            Boolean matchIfNoContext, isPreferred;

            // holders for attributes, qualifiers
            Hashtable<String, Source> sources = null;
            HashSet<String> usageContexts = null;
            Hashtable<String, PropertyQualifier> propertyQualifiers = null;

            // As I process the result rows, I will get back duplicates of
            // the property information
            // if the property has more than one qualifer and/or source ,
            // etc.

            while (results.next()) {
                propertyId = results.getString(SQLTableConstants.TBLCOL_PROPERTYID);

                if (newProperty == null || !propertyId.equals(newProperty.getPropertyId())) {
                    // not equal means we have started a new property
                    property = results.getString(si.getSQLTableConstants().propertyOrPropertyName);
                    propertyType = results.getString(SQLTableConstants.TBLCOL_PROPERTYTYPE);
                    propertyValue = results.getString(SQLTableConstants.TBLCOL_PROPERTYVALUE);
                    language = results.getString(SQLTableConstants.TBLCOL_LANGUAGE);
                    presentationFormat = results
                            .getString(si.getSQLTableConstants().formatOrPresentationFormat);
                    degreeOfFidelity = results.getString(SQLTableConstants.TBLCOL_DEGREEOFFIDELITY);
                    representationalForm = results.getString(SQLTableConstants.TBLCOL_REPRESENTATIONALFORM);
                    matchIfNoContext = DBUtility.getBooleanFromResultSet(results,
                            SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT);
                    isPreferred = DBUtility.getBooleanFromResultSet(results,
                            SQLTableConstants.TBLCOL_ISPREFERRED);

                    // add all of the collected sources, usage contexts, and
                    // qualifiers to
                    // the previous property
                    if (newProperty != null) {
                        newProperty.setSource(sources.values().toArray(new Source[sources.size()]));
                        newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()]));
                        if (!propertyQualifiers.isEmpty())
                            newProperty.setPropertyQualifier(propertyQualifiers.values()
                                    .toArray(new PropertyQualifier[propertyQualifiers.size()]));
                    }

                    // we are starting a new property, so clear out the old
                    // holders.
                    sources = new Hashtable<String, Source>();
                    usageContexts = new HashSet<String>();
                    propertyQualifiers = new Hashtable<String, PropertyQualifier>();

                    // process the property portion of the result
                    if (propertyType.equals(SQLTableConstants.TBLCOLVAL_DEFINITION)) {
                        Definition def = new Definition();
                        def.setIsPreferred(isPreferred);
                        def.setLanguage(language);
                        def.setPropertyName(property);
                        def.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        def.setValue(text);
                        definitions.add(def);
                        newProperty = def;
                    } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_PRESENTATION)) {
                        Presentation presentation = new Presentation();
                        presentation.setIsPreferred(isPreferred);
                        presentation.setLanguage(language);
                        presentation.setPropertyName(property);
                        presentation.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        presentation.setValue(text);
                        presentation.setDegreeOfFidelity(degreeOfFidelity);
                        presentation.setMatchIfNoContext(matchIfNoContext);
                        presentation.setRepresentationalForm(representationalForm);

                        presentations.add(presentation);
                        newProperty = presentation;
                    } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_COMMENT)) {
                        Comment comment = new Comment();
                        comment.setLanguage(language);
                        comment.setPropertyName(property);
                        comment.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        comment.setValue(text);
                        comments.add(comment);
                        newProperty = comment;
                    } else {
                        Property theProperty = new Property();
                        theProperty.setLanguage(language);
                        theProperty.setPropertyName(property);
                        theProperty.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        theProperty.setValue(text);
                        properties.add(theProperty);
                        newProperty = theProperty;
                    }

                    newProperty.setPropertyType(propertyType);

                    if (si.supports2009Model()) {

                        String owner = results.getString(SQLTableConstants.TBLCOL_OWNER);
                        String status = results.getString(SQLTableConstants.TBLCOL_STATUS);
                        Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE);
                        Timestamp expirationDate = results
                                .getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE);
                        String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID);
                        String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID);
                        String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE);
                        String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER);

                        if (revisionId != null) {
                            EntryState es = new EntryState();
                            if (!StringUtils.isBlank(changeType)) {
                                es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType));
                            }
                            es.setContainingRevision(revisionId);
                            es.setPrevRevision(prevRevisionId);
                            es.setRelativeOrder(computeRelativeOrder(relativeOrder));

                            newProperty.setEntryState(es);
                        }

                        if (owner != null) {
                            newProperty.setOwner(owner);
                        }

                        if (status != null)
                            newProperty.setStatus(status);
                        if (effectiveDate != null)
                            newProperty.setEffectiveDate(effectiveDate);
                        if (expirationDate != null)
                            newProperty.setExpirationDate(expirationDate);
                    }
                }

                String type = null;
                String value = null;
                String val1 = null;
                String val2 = null;

                // collect values from the multiAttributes table
                type = results.getString(SQLTableConstants.TBLCOL_TYPENAME);
                value = results.getString(SQLTableConstants.TBLCOL_ATTRIBUTEVALUE);
                val1 = results.getString(SQLTableConstants.TBLCOL_VAL1);
                if (StringUtils.isBlank(val1))
                    val1 = null;
                val2 = results.getString(SQLTableConstants.TBLCOL_VAL2);
                if (StringUtils.isBlank(val2))
                    val2 = null;

                // hashsets to remove dupes (table doesn't allow dupes, but
                // left join will create some)
                if (type != null) {
                    if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_SOURCE)) {
                        if (!sources.containsKey(createUniqueKeyForSource(value, val1))) {
                            Source s = new Source();
                            s.setContent(value);
                            s.setRole(val2);
                            s.setSubRef(val1);
                            sources.put(createUniqueKeyForSource(value, val1), s);
                        }
                    } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_USAGECONTEXT)) {
                        usageContexts.add(value);
                    } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_QUALIFIER)) {
                        // nulls are a side affect of left join
                        if (!propertyQualifiers.containsKey(val1 + ":" + value)) {
                            PropertyQualifier pq = new PropertyQualifier();
                            Text txt = new Text();
                            txt.setContent(val1);
                            pq.setValue(txt);
                            pq.setPropertyQualifierName(value);
                            propertyQualifiers.put(val1 + ":" + value, pq);
                        }
                    } else {
                        getLogger().warn("There is invalid data in the 'typeName' column in the table "
                                + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES)
                                + " for the concept code: " + code + " propertyId: " + propertyId
                                + " codingSchemeName: " + internalCodingSchemeName);
                    }
                }
            }

            // add all of the collected sources, usage contexts, and
            // qualifiers to
            // the previous property before exiting ...
            if (newProperty != null) {
                newProperty.setSource(sources.values().toArray(new Source[sources.size()]));
                newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()]));
                if (!propertyQualifiers.isEmpty())
                    newProperty.setPropertyQualifier(propertyQualifiers.values()
                            .toArray(new PropertyQualifier[propertyQualifiers.size()]));
            }
            results.close();
        } finally {
            si.checkInPreparedStatement(getEntityCode);
            si.checkInPreparedStatement(getEntityProperties);
            si.checkInPreparedStatement(getPropertyLinks);
        }

        concept.setComment(comments.toArray(new Comment[comments.size()]));
        concept.setDefinition(definitions.toArray(new Definition[definitions.size()]));
        concept.setPropertyLink(links.toArray(new PropertyLink[links.size()]));
        concept.setPresentation(presentations.toArray(new Presentation[presentations.size()]));
        concept.setProperty(properties.toArray(new Property[properties.size()]));
        return concept;
    } catch (MissingResourceException e) {
        throw e;
    } catch (Exception e) {
        throw new UnexpectedInternalError("There was an unexpected internal error.", e);
    }
}

From source file:edu.ku.brc.specify.tasks.WorkbenchTask.java

/**
 * This filters out all non-image files per the image filter and adds them to the Vector.
 * @param files the list of files//from  w  w w . j  a v  a  2  s .  c  o  m
 * @param fileList the returned Vector of image files
 * @param imageFilter the filter to use to weed out non-image files
 * @return true if it should continue, false to stop
 */
protected boolean filterSelectedFileNames(final File[] files, final Vector<File> fileList,
        final ImageFilter imageFilter) {
    if (files == null || files.length == 0) {
        return false;
    }

    Hashtable<String, Boolean> badFileExts = new Hashtable<String, Boolean>();

    for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) {
            String fileName = files[i].getName();
            if (imageFilter.isImageFile(fileName)) {
                fileList.add(files[i]);
            } else {
                badFileExts.put(FilenameUtils.getExtension(fileName), true);
            }
        }
    }

    // No check to see if we had any bad files and warn the user about them
    if (badFileExts.size() > 0) {
        StringBuffer badExtStrBuf = new StringBuffer();
        for (String ext : badFileExts.keySet()) {
            if (badExtStrBuf.length() > 0)
                badExtStrBuf.append(", ");
            badExtStrBuf.append(ext);
        }

        // Now, if none of the files were good we tell them and then quit the import task
        if (fileList.size() == 0) {
            JOptionPane.showMessageDialog(UIRegistry.getMostRecentWindow(),
                    String.format(getResourceString("WB_WRONG_IMG_NO_IMAGES"),
                            new Object[] { badExtStrBuf.toString() }),
                    UIRegistry.getResourceString("WARNING"), JOptionPane.ERROR_MESSAGE);
            return false;

        }

        // So we know we have at least one good image file type
        // So let them choose if they want to continue.
        Object[] options = { getResourceString("Continue"), getResourceString("Stop") };

        if (JOptionPane.showOptionDialog(UIRegistry.getMostRecentWindow(),
                String.format(getResourceString("WB_WRONG_IMG_SOME_IMAGES"),
                        new Object[] { badExtStrBuf.toString() }),
                title, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[1]) == JOptionPane.NO_OPTION) {
            return false;
        }
    }
    return true;
}

From source file:org.lexevs.dao.database.sqlimplementedmethods.SQLImplementedMethodsDao.java

/**
 * Builds the coded entry.//ww  w .j  a v a  2s .c o  m
 * 
 * @param internalCodingSchemeName the internal coding scheme name
 * @param internalVersionString the internal version string
 * @param code the code
 * @param namespace the namespace
 * @param restrictToProperties the restrict to properties
 * @param restrictToPropertyTypes the restrict to property types
 * 
 * @return the entity
 * 
 * @throws UnexpectedInternalError the unexpected internal error
 * @throws MissingResourceException the missing resource exception
 */
public Entity buildCodedEntry(String internalCodingSchemeName, String internalVersionString, String code,
        String namespace, LocalNameList restrictToProperties, PropertyType[] restrictToPropertyTypes)
        throws UnexpectedInternalError, MissingResourceException {

    try {
        Entity concept = new Entity();
        concept.setEntityCode(code);

        SQLInterface si = resourceManager.getSQLInterface(internalCodingSchemeName, internalVersionString);

        //if the namespace is null (and its 2009 model), set it to the default (which is
        //equal to the codingSchemeName.
        //This shouldn't ever happen -- all classes that call this method should provide
        //a namespace.
        if (si.supports2009Model() && StringUtils.isBlank(namespace)) {
            namespace = internalCodingSchemeName;
        }

        ArrayList<Definition> definitions = new ArrayList<Definition>();
        ArrayList<Presentation> presentations = new ArrayList<Presentation>();
        ArrayList<Property> properties = new ArrayList<Property>();
        ArrayList<Comment> comments = new ArrayList<Comment>();

        ArrayList<PropertyLink> links = new ArrayList<PropertyLink>();

        PreparedStatement getEntityCode = null;
        PreparedStatement getEntityType = null;
        PreparedStatement getEntityProperties = null;
        PreparedStatement getPropertyLinks = null;

        try {
            StringBuffer buildEntity = new StringBuffer();

            buildEntity
                    .append("Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY) + " {AS} t1 ");

            if (si.supports2009Model()) {
                buildEntity.append("left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} t2 "
                        + "on t1." + SQLTableConstants.TBLCOL_ENTRYSTATEID + " = t2."
                        + SQLTableConstants.TBLCOL_ENTRYSTATEID);
            }

            buildEntity.append(" where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND "
                    + si.getSQLTableConstants().entityCodeOrId + " = ?");

            if (si.supports2009Model()) {
                buildEntity.append(" AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");
            }

            getEntityCode = si.modifyAndCheckOutPreparedStatement(buildEntity.toString());

            getEntityCode.setString(1, internalCodingSchemeName);
            getEntityCode.setString(2, code);
            if (si.supports2009Model()) {
                getEntityCode.setString(3, namespace);
            }

            ResultSet results = getEntityCode.executeQuery();

            // one and only one result
            if (results.next()) {
                concept.setIsDefined(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISDEFINED));
                concept.setIsAnonymous(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISANONYMOUS));
                concept.setIsActive(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISACTIVE));

                if (!si.supports2009Model()) {
                    concept.setStatus(results.getString(SQLTableConstants.TBLCOL_CONCEPTSTATUS));
                } else {
                    concept.setEntityCodeNamespace(namespace);
                }

                EntityDescription ed = new EntityDescription();
                ed.setContent(results.getString(SQLTableConstants.TBLCOL_ENTITYDESCRIPTION));
                concept.setEntityDescription(ed);

                if (si.supports2009Model()) {
                    String owner = results.getString(SQLTableConstants.TBLCOL_OWNER);
                    String status = results.getString(SQLTableConstants.TBLCOL_STATUS);
                    Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE);
                    Timestamp expirationDate = results.getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE);
                    String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID);
                    String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID);
                    String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE);
                    String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER);

                    EntryState es = new EntryState();

                    if (!StringUtils.isBlank(changeType)) {
                        es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType));
                    }
                    es.setContainingRevision(revisionId);
                    es.setPrevRevision(prevRevisionId);

                    es.setRelativeOrder(computeRelativeOrder(relativeOrder));

                    concept.setEntryState(es);

                    if (owner != null) {
                        concept.setOwner(owner);
                    }
                    concept.setStatus(status);
                    concept.setEffectiveDate(effectiveDate);
                    concept.setExpirationDate(expirationDate);
                }
            }

            results.close();
            si.checkInPreparedStatement(getEntityCode);

            if (si.supports2009Model()) {
                getEntityType = si.checkOutPreparedStatement(
                        "Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY_TYPE) + " where "
                                + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND "
                                + si.getSQLTableConstants().entityCodeOrId + " = ? AND "
                                + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");

                getEntityType.setString(1, internalCodingSchemeName);
                getEntityType.setString(2, code);
                getEntityType.setString(3, namespace);

                results = getEntityType.executeQuery();
                while (results.next()) {
                    concept.addEntityType(results.getString(SQLTableConstants.TBLCOL_ENTITYTYPE));
                }

                results.close();
                si.checkInPreparedStatement(getEntityType);
            } else {
                concept.addEntityType(SQLTableConstants.ENTITYTYPE_CONCEPT);
            }

            // populate the property links
            String addWhereSegment = (!si.supports2009Model()
                    ? (si.getSQLTableConstants().entityType + " = '" + SQLTableConstants.ENTITYTYPE_CONCEPT
                            + "' and ")
                    : "");

            getPropertyLinks = si
                    .checkOutPreparedStatement("Select " + SQLTableConstants.TBLCOL_SOURCEPROPERTYID + ", "
                            + SQLTableConstants.TBLCOL_LINK + ", " + SQLTableConstants.TBLCOL_TARGETPROPERTYID
                            + " from " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_LINKS) + " where "
                            + addWhereSegment + si.getSQLTableConstants().entityCodeOrEntityId + " = ? and "
                            + si.getSQLTableConstants().codingSchemeNameOrId + " = ?");
            getPropertyLinks.setString(1, code);
            getPropertyLinks.setString(2, internalCodingSchemeName);

            results = getPropertyLinks.executeQuery();

            while (results.next()) {
                String sourcePropertyId = results.getString(SQLTableConstants.TBLCOL_SOURCEPROPERTYID);
                String link = results.getString(SQLTableConstants.TBLCOL_LINK);
                String targetPropertyId = results.getString(SQLTableConstants.TBLCOL_TARGETPROPERTYID);

                PropertyLink pl = new PropertyLink();
                pl.setPropertyLink(link);
                pl.setSourceProperty(sourcePropertyId);
                pl.setTargetProperty(targetPropertyId);
                links.add(pl);
            }
            results.close();
            si.checkInPreparedStatement(getPropertyLinks);

            // codedEntry.setModVersion(null);

            StringBuffer propertyQuery = new StringBuffer();

            // I'm constructing a left join query to get the property
            // results I need from 3 (or 2 in 1.5 table version) different
            // tables at once, rather than doing a query on each.

            propertyQuery.append("SELECT a." + SQLTableConstants.TBLCOL_PROPERTYID + ", a."
                    + SQLTableConstants.TBLCOL_PROPERTYNAME + ", a." + SQLTableConstants.TBLCOL_LANGUAGE
                    + ", a." + SQLTableConstants.TBLCOL_FORMAT + ", a." + SQLTableConstants.TBLCOL_ISPREFERRED
                    + ", a." + SQLTableConstants.TBLCOL_DEGREEOFFIDELITY + ", a."
                    + SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT + ", a."
                    + SQLTableConstants.TBLCOL_REPRESENTATIONALFORM + ", a."
                    + SQLTableConstants.TBLCOL_PROPERTYVALUE + ", a." + SQLTableConstants.TBLCOL_PROPERTYTYPE
                    + (si.supports2009Model() ? (", a." + SQLTableConstants.TBLCOL_ENTRYSTATEID) : "")
                    + (si.supports2009Model() ? ", es.*" : "") + ", b." + SQLTableConstants.TBLCOL_TYPENAME
                    + ", b." + SQLTableConstants.TBLCOL_ATTRIBUTEVALUE + ", b." + SQLTableConstants.TBLCOL_VAL1
                    + ", b." + SQLTableConstants.TBLCOL_VAL2);

            propertyQuery.append(" FROM ");

            String codingSchemeName = si.getSQLTableConstants().codingSchemeNameOrId;
            String concptCode = si.getSQLTableConstants().entityCodeOrEntityId;

            propertyQuery.append(si.getTableName(SQLTableConstants.ENTITY_PROPERTY) + " {AS} a ");
            propertyQuery.append(
                    " left join " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES));
            propertyQuery.append(" {AS} b on a." + codingSchemeName + " = b." + codingSchemeName + " and a."
                    + concptCode + " = b." + concptCode + " and a." + SQLTableConstants.TBLCOL_PROPERTYID
                    + " = b." + SQLTableConstants.TBLCOL_PROPERTYID);

            if (si.supports2009Model()) {
                propertyQuery
                        .append(" left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} es ");
                propertyQuery.append("on a." + SQLTableConstants.TBLCOL_ENTRYSTATEID);
                propertyQuery.append(" = es." + SQLTableConstants.TBLCOL_ENTRYSTATEID);
            }

            propertyQuery.append(" where a." + concptCode + " = ? " + "and a." + codingSchemeName + " = ?");
            if (si.supports2009Model()) {
                propertyQuery.append(" and a." + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");
            }

            if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) {
                propertyQuery.append(" AND (");
                for (int i = 0; i < restrictToProperties.getEntryCount(); i++) {
                    propertyQuery.append("  " + si.getSQLTableConstants().propertyOrPropertyName + " = ? ");
                    if (i + 1 < restrictToProperties.getEntryCount()) {
                        propertyQuery.append(" OR ");
                    }
                }
                propertyQuery.append(")");

            }

            if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) {
                propertyQuery.append(" AND (");

                for (int i = 0; i < restrictToPropertyTypes.length; i++) {
                    propertyQuery.append(" " + SQLTableConstants.TBLCOL_PROPERTYTYPE + " = ? ");
                    if (i + 1 < restrictToPropertyTypes.length) {
                        propertyQuery.append(" OR ");
                    }
                }
                propertyQuery.append(")");

            }

            getEntityProperties = si.modifyAndCheckOutPreparedStatement(propertyQuery.toString());

            int i = 1;
            getEntityProperties.setString(i++, code);
            getEntityProperties.setString(i++, internalCodingSchemeName);
            if (si.supports2009Model()) {
                getEntityProperties.setString(i++, namespace);
            }

            if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) {
                for (int j = 0; j < restrictToProperties.getEntryCount(); j++) {
                    getEntityProperties.setString(i++, restrictToProperties.getEntry(j));
                }
            }
            if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) {
                for (int j = 0; j < restrictToPropertyTypes.length; j++) {
                    String pts = DaoUtility.propertyTypeToStringMap.get(restrictToPropertyTypes[j]);
                    getEntityProperties.setString(i++, pts);
                }
            }

            results = getEntityProperties.executeQuery();

            // store the property from the last row
            org.LexGrid.commonTypes.Property newProperty = null;

            // all of the fields that come from the Property table
            String propertyType, property, propertyValue, language, presentationFormat, degreeOfFidelity,
                    propertyId, representationalForm;
            Boolean matchIfNoContext, isPreferred;

            // holders for attributes, qualifiers
            Hashtable<String, Source> sources = null;
            HashSet<String> usageContexts = null;
            Hashtable<String, PropertyQualifier> propertyQualifiers = null;

            // As I process the result rows, I will get back duplicates of
            // the property information
            // if the property has more than one qualifer and/or source ,
            // etc.

            while (results.next()) {
                propertyId = results.getString(SQLTableConstants.TBLCOL_PROPERTYID);

                if (newProperty == null || !propertyId.equals(newProperty.getPropertyId())) {
                    // not equal means we have started a new property
                    property = results.getString(si.getSQLTableConstants().propertyOrPropertyName);
                    propertyType = results.getString(SQLTableConstants.TBLCOL_PROPERTYTYPE);
                    propertyValue = results.getString(SQLTableConstants.TBLCOL_PROPERTYVALUE);
                    language = results.getString(SQLTableConstants.TBLCOL_LANGUAGE);
                    presentationFormat = results
                            .getString(si.getSQLTableConstants().formatOrPresentationFormat);
                    degreeOfFidelity = results.getString(SQLTableConstants.TBLCOL_DEGREEOFFIDELITY);
                    representationalForm = results.getString(SQLTableConstants.TBLCOL_REPRESENTATIONALFORM);
                    matchIfNoContext = DBUtility.getBooleanFromResultSet(results,
                            SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT);
                    isPreferred = DBUtility.getBooleanFromResultSet(results,
                            SQLTableConstants.TBLCOL_ISPREFERRED);

                    // add all of the collected sources, usage contexts, and
                    // qualifiers to
                    // the previous property
                    if (newProperty != null) {
                        newProperty.setSource(sources.values().toArray(new Source[sources.size()]));
                        newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()]));
                        if (!propertyQualifiers.isEmpty())
                            newProperty.setPropertyQualifier(propertyQualifiers.values()
                                    .toArray(new PropertyQualifier[propertyQualifiers.size()]));
                    }

                    // we are starting a new property, so clear out the old
                    // holders.
                    sources = new Hashtable<String, Source>();
                    usageContexts = new HashSet<String>();
                    propertyQualifiers = new Hashtable<String, PropertyQualifier>();

                    // process the property portion of the result
                    if (propertyType.equals(SQLTableConstants.TBLCOLVAL_DEFINITION)) {
                        Definition def = new Definition();
                        def.setIsPreferred(isPreferred);
                        def.setLanguage(language);
                        def.setPropertyName(property);
                        def.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        def.setValue(text);
                        definitions.add(def);
                        newProperty = def;
                    } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_PRESENTATION)) {
                        Presentation presentation = new Presentation();
                        presentation.setIsPreferred(isPreferred);
                        presentation.setLanguage(language);
                        presentation.setPropertyName(property);
                        presentation.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        presentation.setValue(text);
                        presentation.setDegreeOfFidelity(degreeOfFidelity);
                        presentation.setMatchIfNoContext(matchIfNoContext);
                        presentation.setRepresentationalForm(representationalForm);

                        presentations.add(presentation);
                        newProperty = presentation;
                    } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_COMMENT)) {
                        Comment comment = new Comment();
                        comment.setLanguage(language);
                        comment.setPropertyName(property);
                        comment.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        comment.setValue(text);
                        comments.add(comment);
                        newProperty = comment;
                    } else {
                        Property theProperty = new Property();
                        theProperty.setLanguage(language);
                        theProperty.setPropertyName(property);
                        theProperty.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        theProperty.setValue(text);
                        properties.add(theProperty);
                        newProperty = theProperty;
                    }

                    newProperty.setPropertyType(propertyType);

                    if (si.supports2009Model()) {

                        String owner = results.getString(SQLTableConstants.TBLCOL_OWNER);
                        String status = results.getString(SQLTableConstants.TBLCOL_STATUS);
                        Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE);
                        Timestamp expirationDate = results
                                .getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE);
                        String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID);
                        String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID);
                        String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE);
                        String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER);

                        if (revisionId != null) {
                            EntryState es = new EntryState();
                            if (!StringUtils.isBlank(changeType)) {
                                es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType));
                            }
                            es.setContainingRevision(revisionId);
                            es.setPrevRevision(prevRevisionId);
                            es.setRelativeOrder(computeRelativeOrder(relativeOrder));

                            newProperty.setEntryState(es);
                        }

                        if (owner != null) {
                            newProperty.setOwner(owner);
                        }

                        if (status != null)
                            newProperty.setStatus(status);
                        if (effectiveDate != null)
                            newProperty.setEffectiveDate(effectiveDate);
                        if (expirationDate != null)
                            newProperty.setExpirationDate(expirationDate);
                    }
                }

                String type = null;
                String value = null;
                String val1 = null;
                String val2 = null;

                // collect values from the multiAttributes table
                type = results.getString(SQLTableConstants.TBLCOL_TYPENAME);
                value = results.getString(SQLTableConstants.TBLCOL_ATTRIBUTEVALUE);
                val1 = results.getString(SQLTableConstants.TBLCOL_VAL1);
                if (StringUtils.isBlank(val1))
                    val1 = null;
                val2 = results.getString(SQLTableConstants.TBLCOL_VAL2);
                if (StringUtils.isBlank(val2))
                    val2 = null;

                // hashsets to remove dupes (table doesn't allow dupes, but
                // left join will create some)
                if (type != null) {
                    if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_SOURCE)) {
                        if (!sources.containsKey(createUniqueKeyForSource(value, val1))) {
                            Source s = new Source();
                            s.setContent(value);
                            s.setRole(val2);
                            s.setSubRef(val1);
                            sources.put(createUniqueKeyForSource(value, val1), s);
                        }
                    } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_USAGECONTEXT)) {
                        usageContexts.add(value);
                    } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_QUALIFIER)) {
                        // nulls are a side affect of left join
                        if (!propertyQualifiers.containsKey(val1 + ":" + value)) {
                            PropertyQualifier pq = new PropertyQualifier();
                            Text txt = new Text();
                            txt.setContent(val1);
                            pq.setValue(txt);
                            pq.setPropertyQualifierName(value);
                            propertyQualifiers.put(val1 + ":" + value, pq);
                        }
                    } else {
                        getLogger().warn("There is invalid data in the 'typeName' column in the table "
                                + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES)
                                + " for the concept code: " + code + " propertyId: " + propertyId
                                + " codingSchemeName: " + internalCodingSchemeName);
                    }
                }
            }

            // add all of the collected sources, usage contexts, and
            // qualifiers to
            // the previous property before exiting ...
            if (newProperty != null) {
                newProperty.setSource(sources.values().toArray(new Source[sources.size()]));
                newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()]));
                if (!propertyQualifiers.isEmpty())
                    newProperty.setPropertyQualifier(propertyQualifiers.values()
                            .toArray(new PropertyQualifier[propertyQualifiers.size()]));
            }
            results.close();
        } finally {
            si.checkInPreparedStatement(getEntityCode);
            si.checkInPreparedStatement(getEntityProperties);
            si.checkInPreparedStatement(getPropertyLinks);
        }

        concept.setComment(comments.toArray(new Comment[comments.size()]));
        concept.setDefinition(definitions.toArray(new Definition[definitions.size()]));
        concept.setPropertyLink(links.toArray(new PropertyLink[links.size()]));
        concept.setPresentation(presentations.toArray(new Presentation[presentations.size()]));
        concept.setProperty(properties.toArray(new Property[properties.size()]));
        return concept;
    } catch (MissingResourceException e) {
        throw e;
    } catch (Exception e) {
        throw new UnexpectedInternalError("There was an unexpected internal error.", e);
    }
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

/**
 * @param p_dispositionLists//www.j  a v a2  s . c  o  m
 *            - Map of List of WorkflowTaskInstances keyed by one of
 *            WorkflowConstant.IS_NEW or IS_DELETED.
 * @param p_modified
 *            Tasks Hashtable of modified tasks - keyed by taskid. Value is
 *            TaskInfoBean with modifications
 */
@SuppressWarnings("unchecked")
private void persistWorkflowTaskInstanceChanges(Map p_dispositionLists, Hashtable p_modifiedTasks,
        WorkflowInstance p_wfInstance, List p_wfTaskInfos, Session p_session, Workflow p_workflowClone)
        throws Exception {
    List added = (List) p_dispositionLists.get(WorkflowConstants.IS_NEW);
    if (added != null && added.size() > 0) {
        createTasks(p_session, new Vector(added), p_modifiedTasks, p_workflowClone, p_wfTaskInfos);
    }
    List deleted = (List) p_dispositionLists.get(WorkflowConstants.IS_DELETED);
    if (deleted != null && deleted.size() > 0) {
        deleteTasks(p_session, new Vector(deleted), p_workflowClone, p_wfTaskInfos);
    }

    if (p_modifiedTasks != null && p_modifiedTasks.size() > 0) {
        modifyTasks(p_session, p_modifiedTasks, p_workflowClone, p_wfTaskInfos);
    }
}

From source file:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java

/**
 * _more_//from   w ww.  j a  va 2 s .co  m
 * 
 * @param stormInfo
 *            _more_
 * @param tracks
 *            _more_
 * @param trackFile
 *            _more_
 * @param waysToUse
 *            _more_
 * @param throwError
 *            _more_
 * 
 * 
 * @return _more_
 * @throws Exception
 *             _more_
 */
private boolean readTracks(StormInfo stormInfo, StormTrackCollection tracks, String trackFile,
        Hashtable<String, Boolean> waysToUse, boolean throwError) throws Exception {

    long t1 = System.currentTimeMillis();
    byte[] bytes = readFile(trackFile, true);
    long t2 = System.currentTimeMillis();
    // System.err.println("read time:" + (t2 - t1));
    boolean isZip = trackFile.endsWith(".gz");
    if ((bytes == null) && isZip) {
        String withoutGZ = trackFile.substring(0, trackFile.length() - 3);
        bytes = readFile(withoutGZ, true);
        isZip = false;
    }

    if (bytes == null) {
        if (throwError) {
            throw new BadDataException("Unable to read track file:" + trackFile);
        }
        return false;
    }

    if (isZip) {
        GZIPInputStream zin = new GZIPInputStream(new ByteArrayInputStream(bytes));
        bytes = IOUtil.readBytes(zin);
        zin.close();
    }
    GregorianCalendar convertCal = new GregorianCalendar(DateUtil.TIMEZONE_GMT);
    convertCal.clear();

    String trackData = new String(bytes);
    List lines = StringUtil.split(trackData, "\n", true, true);
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHH");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    Hashtable trackMap = new Hashtable();
    Real altReal = new Real(RealType.Altitude, 0);
    // System.err.println("obs:" + lines.size());
    /*
     * Hashtable okWays = new Hashtable(); okWays.put(WAY_CARQ, "");
     * okWays.put(WAY_WRNG, ""); okWays.put(WAY_BEST, ""); okWays.put("ETA",
     * ""); okWays.put("NGX", ""); okWays.put("BAMS", "");
     */
    Hashtable seenDate = new Hashtable();
    initParams();
    int xcnt = 0;
    for (int i = 0; i < lines.size(); i++) {
        String line = (String) lines.get(i);
        if (i == 0) {
            // System.err.println(line);
        }
        List toks = StringUtil.split(line, ",", true);
        /*
         * System.err.println(toks.size() + " " + BASEIDX);
         * if(toks.size()<BASEIDX-1) { System.err.println("bad line:" +
         * line); continue; } else { System.err.println("good line:" +
         * line); }
         */

        // BASIN,CY,YYYYMMDDHH,TECHNUM,TECH,TAU,LatN/S,LonE/W,VMAX,MSLP,TY,RAD,WINDCODE,RAD1,RAD2,RAD3,RAD4,RADP,RRP,MRD,GUSTS,EYE,SUBREGION,MAXSEAS,INITIALS,DIR,SPEED,STORMNAME,DEPTH,SEAS,SEASCODE,SEAS1,SEAS2,SEAS3,SEAS4
        // AL, 01, 2007050612, , BEST, 0, 355N, 740W, 35, 1012, EX, 34, NEQ,
        // 0, 0, 0, 120,
        // AL, 01, 2007050812, 01, CARQ, -24, 316N, 723W, 55, 0, DB, 34,
        // AAA, 0, 0, 0, 0,

        String dateString = (String) toks.get(IDX_YYYYMMDDHH);
        String wayString = (String) toks.get(IDX_TECH);
        // if (okWays.get(wayString) == null) {
        // continue;
        // }
        boolean isBest = wayString.equals(WAY_BEST);
        boolean isWarning = wayString.equals(WAY_WRNG);
        boolean isCarq = wayString.equals(WAY_CARQ);

        int category = ((IDX_TY < toks.size()) ? getCategory((String) toks.get(IDX_TY)) : CATEGORY_XX);
        if (category != CATEGORY_XX) {
            // System.err.println("cat:" + category);
        }

        String fhour = (String) toks.get(IDX_TAU);
        int forecastHour = new Integer(fhour).intValue();
        // A hack - we've seen some atfc files that have a 5 character
        // forecast hour
        // right padded with "00", eg., 01200
        if ((fhour.length() == 5) && (forecastHour > 100)) {
            forecastHour = forecastHour / 100;
        }

        if (isWarning || isCarq) {
            forecastHour = -forecastHour;
        }

        // Check for unique dates for this way
        String dttmkey = wayString + "_" + dateString + "_" + forecastHour;
        if (seenDate.get(dttmkey) != null) {
            continue;
        }
        seenDate.put(dttmkey, dttmkey);

        Date dttm = fmt.parse(dateString);
        convertCal.setTime(dttm);
        String key;
        Way way = getWay(wayString, null);
        if (!isBest && (waysToUse != null) && (waysToUse.size() > 0) && (waysToUse.get(wayString) == null)) {
            continue;
        }

        if (isBest) {
            key = wayString;
        } else {
            key = wayString + "_" + dateString;
            convertCal.add(Calendar.HOUR_OF_DAY, forecastHour);
        }
        dttm = convertCal.getTime();
        StormTrack track = (StormTrack) trackMap.get(key);
        if (track == null) {
            way = (isBest ? Way.OBSERVATION : way);
            track = new StormTrack(stormInfo, addWay(way), new DateTime(dttm), obsParams);
            trackMap.put(key, track);
            tracks.addTrack(track);
        }
        String latString = (String) toks.get(IDX_LAT);
        String lonString = (String) toks.get(IDX_LON);
        String t = latString + " " + lonString;

        boolean south = latString.endsWith("S");
        boolean west = lonString.endsWith("W");
        double latitude = Double.parseDouble(latString.substring(0, latString.length() - 1)) / 10.0;
        double longitude = Double.parseDouble(lonString.substring(0, lonString.length() - 1)) / 10.0;
        if (south) {
            latitude = -latitude;
        }
        if (west) {
            longitude = -longitude;
        }

        EarthLocation elt = new EarthLocationLite(new Real(RealType.Latitude, latitude),
                new Real(RealType.Longitude, longitude), altReal);

        List<Real> attributes = new ArrayList<Real>();

        double windspeed = ((IDX_VMAX < toks.size()) ? getDouble((String) toks.get(IDX_VMAX)) : Double.NaN);
        double pressure = ((IDX_MSLP < toks.size()) ? getDouble((String) toks.get(IDX_MSLP)) : Double.NaN);
        attributes.add(PARAM_STORMCATEGORY.getReal((double) category));
        attributes.add(PARAM_MINPRESSURE.getReal(pressure));
        attributes.add(PARAM_MAXWINDSPEED_KTS.getReal(windspeed));

        StormTrackPoint stp = new StormTrackPoint(elt, new DateTime(dttm), forecastHour, attributes);

        track.addPoint(stp);
    }
    return true;
}

From source file:org.unitime.timetable.solver.TimetableDatabaseLoader.java

private void loadCommittedStudentConflicts(org.hibernate.Session hibSession, Set<Long> offeringsToAvoid) {
    //Load all committed assignment - student relations that may be relevant
    List<Object[]> assignmentEnrollments = (List<Object[]>) hibSession
            .createQuery("select distinct a, e.studentId, io.uniqueId from "
                    + "Solution s inner join s.assignments a inner join s.studentEnrollments e inner join a.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering io "
                    + "where " + "s.commited=true and s.owner.session.uniqueId=:sessionId and s.owner not in ("
                    + iSolverGroupIds + ") and " + "a.clazz=e.clazz")
            .setLong("sessionId", iSessionId.longValue()).list();

    // Filter out relevant relations (relations that are for loaded students)
    Hashtable<Assignment, Set<Student>> assignments = new Hashtable<Assignment, Set<Student>>();
    for (Object[] result : assignmentEnrollments) {
        Assignment assignment = (Assignment) result[0];
        Long studentId = (Long) result[1];
        Long offeringId = (Long) result[2];
        if (offeringsToAvoid.contains(offeringId))
            continue;
        Student student = (Student) iStudents.get(studentId);
        if (student != null) {
            Set<Student> students = assignments.get(assignment);
            if (students == null) {
                students = new HashSet<Student>();
                assignments.put(assignment, students);
            }//from  w w w. j  a  va  2 s .  c om
            students.add(student);
        }
    }

    // Ensure no assignment-class relation is got from the cache
    for (Iterator i1 = assignmentEnrollments.iterator(); i1.hasNext();) {
        Object[] result = (Object[]) i1.next();
        Assignment assignment = (Assignment) result[0];
        if (!assignments.containsKey(assignment))
            hibSession.evict(assignment);
    }

    // Make up the appropriate committed placements and propagate those through the course structure
    iProgress.setPhase("Loading student conflicts with commited solutions ...", assignments.size());
    for (Iterator i1 = assignments.entrySet().iterator(); i1.hasNext();) {
        Map.Entry entry = (Map.Entry) i1.next();
        Assignment assignment = (Assignment) entry.getKey();
        HashSet students = (HashSet) entry.getValue();
        Placement committedPlacement = assignment.getPlacement();
        for (Iterator i2 = students.iterator(); i2.hasNext();) {
            Student student = (Student) i2.next();
            student.addCommitedPlacement(committedPlacement);
        }
        if (!iLectures.containsKey(assignment.getClassId())) {
            iLectures.put(assignment.getClassId(), committedPlacement.variable());
            getModel().addVariable(committedPlacement.variable());
        }
        propagateCommittedAssignment(students, assignment);
        iProgress.incProgress();
    }
}

From source file:edu.ku.brc.specify.web.SpecifyExplorer.java

/**
 * @param out//  ww  w. j a v  a 2  s.co m
 * @param className
 * @param fieldsToSkip
 * @param fieldsOrder
 * @param fieldsAdditional
 */
protected void displaySearchForm(final PrintWriter out, final String fullClassName) {
    try {
        if (StringUtils.isEmpty(template)) {
            out.println("The template file is empty!");
        }
        Class<?> clsObj = Class.forName(fullClassName);
        ClassDisplayInfo cdi = classHash.get(clsObj.getSimpleName());
        String className = cdi.getClassName();

        //fillLabelMap((FormDataObjIFace)clsObj.newInstance(), labelMap);

        int inx = template.indexOf(contentTag);
        String subContent = template.substring(0, inx);
        out.println(StringUtils.replace(subContent, "<!-- Title -->", className + " Search Form"));

        out.println("<form name=plcform action=\"" + servletURL + "\" method=\"GET\" onsubmit=\"\"><br/>\n");
        out.println("<input type=\"hidden\" name=\"cls\" value=\"" + className + "\">\n");
        out.println("<input type=\"hidden\" name=\"id\" value=\"dosearch\">\n");

        out.println("<span style=\"font-size: 14pt;\">" + className + " Search Form</span><br/><br/>\n");
        out.println(
                "<input type=\"radio\" name=\"match\" value=\"OR\" checked=\"checked\"/>Match any of following</input>\n");
        out.println("<input type=\"radio\" name=\"match\" value=\"AND\">Match all of following</input>\n");
        out.println("<br/>\n");

        out.println("<br/>\n");
        out.println("<table style=\"border: 1px gray solid\" cellspacing=\"0\" cellpadding=\"4\">\n");
        out.println("<tr><th class=\"brdr\" align=\"center\" nowrap=\"nowrap\">Field</th>");
        out.println("    <th class=\"brdr\" align=\"center\" nowrap=\"nowrap\">Search Values</th>");
        out.println("    <th class=\"brdr\" align=\"center\" nowrap=\"nowrap\">Hide</th></tr>\n");
        //out.println("<tr><td colspan=\"3\"><hr style=\"color: gray\"/></td></tr>\n");

        Hashtable<Integer, String> ordered = new Hashtable<Integer, String>();
        Vector<String> unOrdered = new Vector<String>();

        StringBuilder sb = new StringBuilder();
        for (Field field : clsObj.getDeclaredFields()) {
            sb.setLength(0);

            String fieldName = field.getName();
            FieldDisplayInfo fdi = cdi.getField(fieldName);

            //System.out.println(fieldName + "  "+fdi+"  "+(fdi != null ? (fdi.isSkipped()+"  "+fdi.isForDisplay()+"  "+fdi.isAvailForSearch()) : ""));
            if (fdi != null && (fdi.isSkipped() && !fdi.isAvailForSearch())) {
                //System.out.println("skipping");
                continue;
            }

            String fldNameLower = fieldName.toLowerCase();
            if (fldNameLower.startsWith(clsObj.getSimpleName().toLowerCase()) && fldNameLower.endsWith("id")) {
                continue;
            }

            try {
                if (!java.util.Collection.class.isAssignableFrom(field.getType())
                        && !org.apache.log4j.Logger.class.isAssignableFrom(field.getType())) {
                    // There has to be a better to check for FormDataObjIFace
                    boolean isOK = true;
                    if (baseClassHash.get(field.getType()) == null) {
                        Object obj = field.getType().newInstance();
                        isOK = !(obj instanceof FormDataObjIFace);
                    }

                    if (isOK) {
                        String labelStr = labelMap.get(fieldName);
                        if (StringUtils.isEmpty(labelStr)) {
                            labelStr = UIHelper.makeNamePretty(fieldName);
                        }

                        Integer index = fdi != null ? fdi.getOrder() : null;

                        int cnt = index == null ? unOrdered.size() : ordered.size();

                        sb.append("<tr><td class=\"BRDRODDEVEN"
                                + "\" align=\"right\" nowrap=\"nowrap\" style=\"border-bottom: 1px gray solid;\"><b>"
                                + labelStr + ":</b></td>");
                        sb.append("<td class=\"BRDRODDEVEN"
                                + "\" nowrap=\"nowrap\" style=\"border-bottom: 1px gray solid;\">"
                                + getControlPanel(field) + "</td>");
                        sb.append("<td class=\"BRDRODDEVEN"
                                + "\" align=\"center\" style=\"border-bottom: 1px gray solid;\">"
                                + getInput(fieldName + "Hide", "checkbox", null) + "</td></tr>\n");
                        cnt++;

                        if (index == null) {
                            unOrdered.add(sb.toString());
                        } else {
                            ordered.put(index, sb.toString());
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        fillRows(out, ordered, unOrdered);

        out.println(
                "<tr><td align=\"center\" colspan=\"2\"><input type=\"submit\" value=\"Search\"></td></tr>\n");
        out.println("</table><br/>");

        out.println("</form>");

        out.println(template.substring(inx + contentTag.length() + 1, template.length()));

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:ucar.unidata.data.storm.AtcfStormDataSource.java

/**
 * _more_//  www  .j a v a2 s .c o  m
 *
 * @param stormInfo _more_
 * @param tracks _more_
 * @param trackFile _more_
 * @param waysToUse _more_
 * @param throwError _more_
 *
 *
 * @return _more_
 * @throws Exception _more_
 */
private boolean readTracks(StormInfo stormInfo, StormTrackCollection tracks, String trackFile,
        Hashtable<String, Boolean> waysToUse, boolean throwError) throws Exception {

    long t1 = System.currentTimeMillis();
    byte[] bytes = readFile(trackFile, true);
    long t2 = System.currentTimeMillis();
    //        System.err.println("read time:" + (t2 - t1));
    boolean isZip = trackFile.endsWith(".gz");
    if ((bytes == null) && isZip) {
        String withoutGZ = trackFile.substring(0, trackFile.length() - 3);
        bytes = readFile(withoutGZ, true);
        isZip = false;
    }

    if (bytes == null) {
        if (throwError) {
            throw new BadDataException("Unable to read track file:" + trackFile);
        }
        return false;
    }

    if (isZip) {
        GZIPInputStream zin = new GZIPInputStream(new ByteArrayInputStream(bytes));
        bytes = IOUtil.readBytes(zin);
        zin.close();
    }
    GregorianCalendar convertCal = new GregorianCalendar(DateUtil.TIMEZONE_GMT);
    convertCal.clear();

    String trackData = new String(bytes);
    List lines = StringUtil.split(trackData, "\n", true, true);
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHH");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    Hashtable trackMap = new Hashtable();
    Real altReal = new Real(RealType.Altitude, 0);
    //        System.err.println("obs:" + lines.size());
    /*        Hashtable okWays = new Hashtable();
    okWays.put(WAY_CARQ, "");
    okWays.put(WAY_WRNG, "");
    okWays.put(WAY_BEST, "");
    okWays.put("ETA", "");
    okWays.put("NGX", "");
    okWays.put("BAMS", "");*/
    Hashtable seenDate = new Hashtable();
    initParams();
    int xcnt = 0;
    // check if the tech num is included
    // some actf files do not have tech num for some reasom.
    List toks1 = StringUtil.split(lines.get(1), ",", true);
    String techNum = (String) toks1.get(IDX_TECHNUM);
    if (techNum.length() > 0 && !techNum.matches("\\d+")) {
        IDX_TECH = IDX_TECH - 1;
        IDX_TAU = IDX_TAU - 1;
        IDX_LAT = IDX_LAT - 1;
        IDX_LON = IDX_LON - 1;
        IDX_VMAX = IDX_VMAX - 1;
        IDX_MSLP = IDX_MSLP - 1;
        IDX_TY = IDX_TY - 1;
    }
    for (int i = 0; i < lines.size(); i++) {
        String line = (String) lines.get(i);
        if (i == 0) {
            //                System.err.println(line);
        }
        List toks = StringUtil.split(line, ",", true);
        /*            System.err.println(toks.size() + " " + BASEIDX);
        if(toks.size()<BASEIDX-1) {
        System.err.println("bad line:" + line);
        continue;
        } else {
        System.err.println("good line:" + line);
        }
        */

        //BASIN,CY,YYYYMMDDHH,TECHNUM,TECH,TAU,LatN/S,LonE/W,VMAX,MSLP,TY,RAD,WINDCODE,RAD1,RAD2,RAD3,RAD4,RADP,RRP,MRD,GUSTS,EYE,SUBREGION,MAXSEAS,INITIALS,DIR,SPEED,STORMNAME,DEPTH,SEAS,SEASCODE,SEAS1,SEAS2,SEAS3,SEAS4
        //AL, 01, 2007050612,   , BEST,   0, 355N,  740W,  35, 1012, EX,  34, NEQ,    0,    0,    0,  120, 
        //AL, 01, 2007050812, 01, CARQ, -24, 316N,  723W,  55,    0, DB,  34, AAA,    0,    0,    0,    0, 

        String dateString = (String) toks.get(IDX_YYYYMMDDHH);
        String wayString = (String) toks.get(IDX_TECH);
        //            if (okWays.get(wayString) == null) {
        //                continue;
        //            }
        boolean isBest = wayString.equals(WAY_BEST);
        boolean isWarning = wayString.equals(WAY_WRNG);
        boolean isCarq = wayString.equals(WAY_CARQ);

        int category = ((IDX_TY < toks.size()) ? getCategory((String) toks.get(IDX_TY)) : CATEGORY_XX);
        if (category != CATEGORY_XX) {
            //                System.err.println("cat:" + category);
        }

        String fhour = (String) toks.get(IDX_TAU);
        int forecastHour = new Integer(fhour).intValue();
        //A hack - we've seen some atfc files that have a 5 character forecast hour
        //right padded with "00", eg., 01200
        if ((fhour.length() == 5) && (forecastHour > 100)) {
            forecastHour = forecastHour / 100;
        }

        if (isWarning || isCarq) {
            forecastHour = -forecastHour;
        }

        //Check for unique dates for this way
        String dttmkey = wayString + "_" + dateString + "_" + forecastHour;
        if (seenDate.get(dttmkey) != null) {
            continue;
        }
        seenDate.put(dttmkey, dttmkey);

        Date dttm = fmt.parse(dateString);
        convertCal.setTime(dttm);
        String key;
        Way way = getWay(wayString, null);
        if (!isBest && (waysToUse != null) && (waysToUse.size() > 0) && (waysToUse.get(wayString) == null)) {
            continue;
        }

        if (isBest) {
            key = wayString;
        } else {
            key = wayString + "_" + dateString;
            convertCal.add(Calendar.HOUR_OF_DAY, forecastHour);
        }
        dttm = convertCal.getTime();
        StormTrack track = (StormTrack) trackMap.get(key);
        if (track == null) {
            way = (isBest ? Way.OBSERVATION : way);
            track = new StormTrack(stormInfo, addWay(way), new DateTime(dttm), obsParams);
            trackMap.put(key, track);
            tracks.addTrack(track);
        }
        String latString = (String) toks.get(IDX_LAT);
        String lonString = (String) toks.get(IDX_LON);
        String t = latString + " " + lonString;

        boolean south = latString.endsWith("S");
        boolean west = lonString.endsWith("W");
        double latitude = Double.parseDouble(latString.substring(0, latString.length() - 1)) / 10.0;
        double longitude = Double.parseDouble(lonString.substring(0, lonString.length() - 1)) / 10.0;
        if (south) {
            latitude = -latitude;
        }
        if (west) {
            longitude = -longitude;
        }

        EarthLocation elt = new EarthLocationLite(new Real(RealType.Latitude, latitude),
                new Real(RealType.Longitude, longitude), altReal);

        List<Real> attributes = new ArrayList<Real>();

        double windspeed = ((IDX_VMAX < toks.size()) ? getDouble((String) toks.get(IDX_VMAX)) : Double.NaN);
        double pressure = ((IDX_MSLP < toks.size()) ? getDouble((String) toks.get(IDX_MSLP)) : Double.NaN);
        attributes.add(PARAM_STORMCATEGORY.getReal((double) category));
        attributes.add(PARAM_MINPRESSURE.getReal(pressure));
        attributes.add(PARAM_MAXWINDSPEED_KTS.getReal(windspeed));

        StormTrackPoint stp = new StormTrackPoint(elt, new DateTime(dttm), forecastHour, attributes);

        track.addPoint(stp);
    }
    return true;
}

From source file:edu.ku.brc.specify.config.SpecifyAppContextMgr.java

/**
 * Sets up the "current" Collection by first checking prefs for the most recent primary key,
 * @param userArg the user object of the current object
 * @param promptForCollection indicates the User should always be asked which Collection to use
 * @param collectionName name of collection to choose (can be null)
 * @return the current Collection or null
 *///from w  ww  . ja va  2  s  . c om
protected Collection setupCurrentCollection(final SpecifyUser userArg, final boolean promptForCollection,
        final String collectionName) {
    DataProviderSessionIFace session = null;
    try {
        AppPreferences remotePrefs = AppPreferences.getRemote();

        session = DataProviderFactory.getInstance().createSession();

        SpecifyUser spUser = session.getData(SpecifyUser.class, "id", userArg.getId(), //$NON-NLS-1$
                DataProviderSessionIFace.CompareType.Equals);

        String alwaysAskPref = "ALWAYS.ASK.COLL"; //$NON-NLS-1$
        boolean askForColl = remotePrefs.getBoolean(alwaysAskPref, true);
        String prefName = mkUserDBPrefName("recent_collection_id"); //$NON-NLS-1$

        // First get the Collections the User has access to.
        Hashtable<String, Pair<String, Integer>> collectionHash = new Hashtable<String, Pair<String, Integer>>();

        String sqlStr = String.format(
                "SELECT DISTINCT cln.CollectionID, cln.CollectionName, cln.DisciplineID FROM collection AS cln "
                        + "Inner Join spprincipal AS p ON cln.UserGroupScopeId = p.userGroupScopeID "
                        + "Inner Join specifyuser_spprincipal AS su_pr ON p.SpPrincipalID = su_pr.SpPrincipalID "
                        + "WHERE su_pr.SpecifyUserID = %d AND GroupSubClass = '%s'", //$NON-NLS-1$
                spUser.getSpecifyUserId(), UserPrincipal.class.getName());

        //log.debug(sqlStr);

        for (Object[] row : BasicSQLUtils.query(sqlStr)) {
            String collName = row[1].toString();
            Integer collId = (Integer) row[0];

            if (collectionHash.get(collName) != null) {
                String dispName = BasicSQLUtils
                        .querySingleObj("SELECT Name FROM discipline WHERE DisciplineID = " + row[2]);
                collName += " - " + dispName;
                if (collectionHash.get(collName) != null) {
                    String sql = "SELECT d.DivisionID FROM collection c INNER JOIN discipline d ON c.DisciplineID = d.UserGroupScopeId WHERE d.DisciplineID = "
                            + row[2];
                    String divName = BasicSQLUtils.querySingleObj(sql);
                    collName += " - " + divName;
                }
            }
            collectionHash.put(collName, new Pair<String, Integer>(collName, collId));
        }

        Pair<String, Integer> currColl = null;

        if (collectionName == null) {
            String recentIds = askForColl || promptForCollection ? null : remotePrefs.get(prefName, null);
            if (StringUtils.isNotEmpty(recentIds)) {
                Vector<Object[]> rows = BasicSQLUtils.query(
                        "SELECT CollectionName, UserGroupScopeId FROM collection WHERE UserGroupScopeId = " //$NON-NLS-1$
                                + recentIds);
                if (rows.size() == 1) {
                    String collName = rows.get(0)[0].toString();
                    Integer collId = (Integer) rows.get(0)[1];
                    currColl = new Pair<String, Integer>(collName, collId);

                } else {
                    log.debug("could NOT find recent ids"); //$NON-NLS-1$
                }
            }

            if (currColl != null && collectionHash.get(currColl.first) == null) {
                currColl = null;
            }
        }

        if (currColl == null || (askForColl && promptForCollection)) {
            if (collectionHash.size() == 1) {
                currColl = collectionHash.elements().nextElement();

            } else if (collectionHash.size() > 0) {
                if (collectionName == null) {
                    List<Pair<String, Integer>> list = new Vector<Pair<String, Integer>>();
                    list.addAll(collectionHash.values());
                    Collections.sort(list, new Comparator<Pair<String, Integer>>() {
                        @Override
                        public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) {
                            return o1.first.compareTo(o2.first);
                        }
                    });

                    int selectColInx = -1;

                    ChooseCollectionDlg colDlg = null;
                    do {
                        colDlg = new ChooseCollectionDlg(list);
                        colDlg.setSelectedIndex(selectColInx);
                        colDlg.createUI();
                        colDlg.pack();
                        Dimension size = colDlg.getSize();
                        size.width = Math.max(size.width, 300);
                        if (size.height < 150) {
                            size.height += 100;
                        }
                        colDlg.setSize(size);

                        UIHelper.centerWindow(colDlg);
                        colDlg.setVisible(true);

                    } while (colDlg.getSelectedObject() == null || colDlg.isCancelled());

                    currColl = colDlg.getSelectedObject();
                } else {
                    Integer colId = BasicSQLUtils.getCount(String.format(
                            "SELECT CollectionID FROM collection WHERE CollectionName = '%s'", collectionName));
                    if (colId != null) {
                        currColl = new Pair<String, Integer>(collectionName, colId);
                    } else {
                        return null;
                    }
                }
            }
        }

        Collection collection = null;

        if (currColl != null) {
            collection = (Collection) session.getData("FROM Collection WHERE id = " + currColl.second);
            if (collection != null) {
                collection.forceLoad();
                remotePrefs.put(prefName, (Long.toString(collection.getCollectionId())));
                remotePrefs.flush();
            }
        }

        if (collection == null) {
            UIRegistry.showLocalizedError(L10N + "ERR_NO_COLL");
            return null;
        }

        setClassObject(Collection.class, collection);

        if (collectionName == null) {
            String colObjStr = "CollectionObject"; //$NON-NLS-1$
            String iconName = remotePrefs.get(FormattingPrefsPanel.getDisciplineImageName(), colObjStr);
            if (StringUtils.isEmpty(iconName) || iconName.equals(colObjStr)) {
                iconName = "colobj_backstop"; //$NON-NLS-1$
            }

            IconManager.aliasImages(iconName, // Source
                    colObjStr); // Dest //$NON-NLS-1$

            IconManager.aliasImages(iconName, // Source
                    colObjStr.toLowerCase()); // Dest //$NON-NLS-1$
        }

        Discipline discipline = collection.getDiscipline();
        session.attach(discipline);

        Institution institution = discipline.getDivision().getInstitution();
        session.attach(institution);

        setClassObject(Institution.class, institution);

        if (!Agent.setUserAgent(spUser, discipline.getDivision())) {
            return null;
        }

        AppContextMgr am = AppContextMgr.getInstance();
        discipline.getTaxonTreeDef().forceLoad();
        am.setClassObject(TaxonTreeDef.class, discipline.getTaxonTreeDef());
        discipline.getGeologicTimePeriodTreeDef().forceLoad();
        am.setClassObject(GeologicTimePeriodTreeDef.class, discipline.getGeologicTimePeriodTreeDef());
        institution.getStorageTreeDef().forceLoad();
        am.setClassObject(StorageTreeDef.class, institution.getStorageTreeDef());
        discipline.getLithoStratTreeDef().forceLoad();
        am.setClassObject(LithoStratTreeDef.class, discipline.getLithoStratTreeDef());
        discipline.getGeographyTreeDef().forceLoad();
        am.setClassObject(GeographyTreeDef.class, discipline.getGeographyTreeDef());

        return collection;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex);
        ex.printStackTrace();
        showLocalizedError(ex.toString()); // Yes, I know it isn't localized.

    } finally {
        if (session != null) {
            session.close();
        }
    }

    return null;

}