Example usage for java.util HashSet size

List of usage examples for java.util HashSet size

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:org.rapla.storage.impl.server.LocalAbstractCachableOperator.java

protected void checkNoDependencies(final UpdateEvent evt, final EntityStore store) throws RaplaException {
    Collection<String> removedIds = evt.getRemoveIds();
    Collection<Entity> storeObjects = new HashSet<Entity>(evt.getStoreObjects());
    HashSet<Entity> dep = new HashSet<Entity>();
    Set<Entity> deletedCategories = getDeletedCategories(storeObjects);
    Collection<Entity> removeEntities = new ArrayList<Entity>();
    for (String id : removedIds) {
        Entity persistant = store.tryResolve(id);
        if (persistant != null) {
            removeEntities.add(persistant);
        }/*ww w  .j  a  v a 2  s  . c  o m*/
    }
    IterableChain<Entity> iteratorChain = new IterableChain<Entity>(deletedCategories, removeEntities);

    for (Entity entity : iteratorChain) {
        // First we add the dependencies from the stored object list
        for (Entity obj : storeObjects) {
            if (obj instanceof EntityReferencer) {
                if (isRefering((EntityReferencer) obj, entity)) {
                    dep.add(obj);
                }
            }
        }
        // we check if the user deletes himself
        if (entity instanceof User) {
            String eventUserId = evt.getUserId();
            if (eventUserId != null && eventUserId.equals(entity.getId())) {
                List<String> emptyList = Collections.emptyList();
                throw new DependencyException(i18n.getString("error.deletehimself"), emptyList);
            }
        }

        // Than we add the dependencies from the cache. It is important that
        // we don't add the dependencies from the stored object list here,
        // because a dependency could be removed in a stored object
        Set<Entity> dependencies = getDependencies(entity, store);
        for (Entity dependency : dependencies) {
            if (!storeObjects.contains(dependency) && !removeEntities.contains(dependency)) {
                // only add the first 21 dependencies;
                if (dep.size() > MAX_DEPENDENCY) {
                    break;
                }
                dep.add(dependency);
            }
        }
    }

    // CKO We skip this check as the admin should have the possibility to deny a user read to allocatables objects even if he has reserved it prior 
    //      for (Entity entity : storeObjects) {
    //         if ( entity.getRaplaType() == Allocatable.TYPE)
    //         {
    //            Allocatable alloc = (Allocatable) entity;
    //            for (Entity reference:getDependencies(entity))
    //            {
    //               if ( reference instanceof Ownable)
    //               {
    //                  User user = ((Ownable) reference).getOwner();
    //                  if (user != null && !alloc.canReadOnlyInformation(user))
    //                  {
    //                     throw new DependencyException( "User " + user.getUsername() + " refers to " + getName(alloc) + ". Read permission is required.", Collections.singleton( getDependentName(reference)));
    //                  }
    //               }
    //            }
    //         }
    //      }

    if (dep.size() > 0) {
        Collection<String> names = new ArrayList<String>();
        for (Entity obj : dep) {
            String string = getDependentName(obj);
            names.add(string);
        }
        throw new DependencyException(getString("error.dependencies"), names.toArray(new String[] {}));
    }
    // Count dynamic-types to ensure that there is least one dynamic type
    // for reservations and one for resources or persons
    checkDynamicType(removeEntities,
            Collections.singleton(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION));
    checkDynamicType(removeEntities,
            new HashSet<String>(
                    Arrays.asList(new String[] { DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,
                            DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON })));
}

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  ww . j a  v  a 2 s  .  com
        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:org.lexevs.dao.database.sqlimplementedmethods.SQLImplementedMethodsDao.java

/**
 * Builds the coded entry.// w w w . j ava  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.sonicle.webtop.contacts.ContactsManager.java

public void syncRemoteCategory(int categoryId, boolean full) throws WTException {
    CoreManager coreMgr = WT.getCoreManager(getTargetProfileId());
    CategoryDAO catDao = CategoryDAO.getInstance();
    final String PENDING_KEY = String.valueOf(categoryId);
    final VCardInput icalInput = new VCardInput();
    Connection con = null;//  w  w w .ja v a 2s  .  c om

    if (pendingRemoteCategorySyncs.putIfAbsent(PENDING_KEY, RunContext.getRunProfileId()) != null) {
        throw new ConcurrentSyncException("Sync activity is already running [{}, {}]", categoryId,
                RunContext.getRunProfileId());
    }

    try {
        //checkRightsOnCategoryFolder(categoryId, "READ");

        con = WT.getConnection(SERVICE_ID, false);
        Category cat = ManagerUtils.createCategory(catDao.selectById(con, categoryId));
        if (cat == null)
            throw new WTException("Category not found [{}]", categoryId);
        if (!Category.Provider.CARDDAV.equals(cat.getProvider())) {
            throw new WTException("Specified category is not remote (CardDAV) [{}]", categoryId);
        }

        // Force a full update if last-sync date is null
        if (cat.getRemoteSyncTimestamp() == null)
            full = true;

        if (Category.Provider.CARDDAV.equals(cat.getProvider())) {
            CategoryRemoteParameters params = LangUtils.deserialize(cat.getParameters(),
                    CategoryRemoteParameters.class);
            if (params == null)
                throw new WTException("Unable to deserialize remote parameters");
            if (params.url == null)
                throw new WTException("Remote URL is undefined");

            CardDav dav = getCardDav(params.username, params.password);

            try {
                DavAddressbook dbook = dav.getAddressbookSyncToken(params.url.toString());
                if (dbook == null)
                    throw new WTException("DAV addressbook not found");

                final boolean syncIsSupported = !StringUtils.isBlank(dbook.getSyncToken());
                final DateTime newLastSync = DateTimeUtils.now();

                if (!full && (syncIsSupported && !StringUtils.isBlank(cat.getRemoteSyncTag()))) { // Partial update using SYNC mode
                    String newSyncToken = dbook.getSyncToken();

                    logger.debug("Querying CardDAV endpoint for changes [{}, {}]", params.url.toString(),
                            cat.getRemoteSyncTag());
                    List<DavSyncStatus> changes = dav.getAddressbookChanges(params.url.toString(),
                            cat.getRemoteSyncTag());
                    logger.debug("Returned {} items", changes.size());

                    try {
                        if (!changes.isEmpty()) {
                            ContactDAO contDao = ContactDAO.getInstance();
                            Map<String, List<Integer>> contactIdsByHref = contDao.selectHrefsByByCategory(con,
                                    categoryId);

                            // Process changes...
                            logger.debug("Processing changes...");
                            HashSet<String> hrefs = new HashSet<>();
                            for (DavSyncStatus change : changes) {
                                String href = FilenameUtils.getName(change.getPath());
                                //String href = change.getPath();

                                if (DavUtil.HTTP_SC_TEXT_OK.equals(change.getResponseStatus())) {
                                    hrefs.add(href);

                                } else { // Card deleted
                                    List<Integer> contactIds = contactIdsByHref.get(href);
                                    Integer contactId = (contactIds != null)
                                            ? contactIds.get(contactIds.size() - 1)
                                            : null;
                                    if (contactId == null) {
                                        logger.warn("Deletion not possible. Card path not found [{}]", PathUtils
                                                .concatPaths(dbook.getPath(), FilenameUtils.getName(href)));
                                        continue;
                                    }
                                    doContactDelete(con, contactId, false);
                                }
                            }

                            // Retrieves events list from DAV endpoint (using multiget)
                            logger.debug("Retrieving inserted/updated cards [{}]", hrefs.size());
                            Collection<String> paths = hrefs.stream().map(
                                    href -> PathUtils.concatPaths(dbook.getPath(), FilenameUtils.getName(href)))
                                    .collect(Collectors.toList());
                            List<DavAddressbookCard> dcards = dav.listAddressbookCards(params.url.toString(),
                                    paths);
                            //List<DavAddressbookCard> dcards = dav.listAddressbookCards(params.url.toString(), hrefs);

                            // Inserts/Updates data...
                            logger.debug("Inserting/Updating cards...");
                            for (DavAddressbookCard dcard : dcards) {
                                String href = FilenameUtils.getName(dcard.getPath());
                                //String href = dcard.getPath();

                                if (logger.isTraceEnabled())
                                    logger.trace("{}", VCardUtils.print(dcard.getCard()));
                                List<Integer> contactIds = contactIdsByHref.get(href);
                                Integer contactId = (contactIds != null) ? contactIds.get(contactIds.size() - 1)
                                        : null;

                                if (contactId != null) {
                                    doContactDelete(con, contactId, false);
                                }
                                final ContactInput ci = icalInput.fromVCardFile(dcard.getCard(), null);
                                ci.contact.setCategoryId(categoryId);
                                ci.contact.setHref(href);
                                ci.contact.setEtag(dcard.geteTag());
                                doContactInsert(coreMgr, con, false, ci.contact, null, true, false);
                            }
                        }

                        catDao.updateRemoteSyncById(con, categoryId, newLastSync, newSyncToken);
                        DbUtils.commitQuietly(con);

                    } catch (Exception ex) {
                        DbUtils.rollbackQuietly(con);
                        throw new WTException(ex, "Error importing vCard");
                    }

                } else { // Full update or partial computing hashes
                    String newSyncToken = null;
                    if (syncIsSupported) { // If supported, saves last sync-token issued by the server
                        newSyncToken = dbook.getSyncToken();
                    }

                    // Retrieves cards from DAV endpoint
                    logger.debug("Retrieving whole list [{}]", params.url.toString());
                    List<DavAddressbookCard> dcards = dav.listAddressbookCards(params.url.toString());
                    logger.debug("Endpoint returns {} items", dcards.size());

                    // Handles data...
                    try {
                        Map<String, VContactHrefSync> syncByHref = null;

                        if (full) {
                            doContactsDeleteByCategory(con, categoryId, false);
                        } else if (!full && !syncIsSupported) {
                            // This hash-map is only needed when syncing using hashes
                            ContactDAO contDao = ContactDAO.getInstance();
                            syncByHref = contDao.viewHrefSyncDataByCategory(con, categoryId);
                        }

                        logger.debug("Processing results...");
                        // Define a simple map in order to check duplicates.
                        // eg. SOGo passes same card twice :(
                        HashSet<String> hrefs = new HashSet<>();
                        for (DavAddressbookCard dcard : dcards) {
                            String href = FilenameUtils.getName(dcard.getPath());
                            //String href = dcard.getPath();
                            String etag = dcard.geteTag();

                            if (logger.isTraceEnabled())
                                logger.trace("{}", VCardUtils.print(dcard.getCard()));
                            if (hrefs.contains(href)) {
                                logger.trace("Card duplicated. Skipped! [{}]", href);
                                continue;
                            }

                            boolean skip = false;
                            Integer matchingContactId = null;

                            if (syncByHref != null) { // Only if... (!full && !syncIsSupported) see above!
                                String prodId = VCardUtils.buildProdId(ManagerUtils.getProductName());
                                String hash = DigestUtils
                                        .md5Hex(new VCardOutput(prodId).write(dcard.getCard(), true));

                                VContactHrefSync hrefSync = syncByHref.remove(href);
                                if (hrefSync != null) { // Href found -> maybe updated item
                                    if (!StringUtils.equals(hrefSync.getEtag(), hash)) {
                                        matchingContactId = hrefSync.getContactId();
                                        etag = hash;
                                        logger.trace("Card updated [{}, {}]", href, hash);
                                    } else {
                                        skip = true;
                                        logger.trace("Card not modified [{}, {}]", href, hash);
                                    }
                                } else { // Href not found -> added item
                                    logger.trace("Card newly added [{}, {}]", href, hash);
                                    etag = hash;
                                }
                            }

                            if (!skip) {
                                final ContactInput ci = icalInput.fromVCardFile(dcard.getCard(), null);
                                ci.contact.setCategoryId(categoryId);
                                ci.contact.setHref(href);
                                ci.contact.setEtag(etag);

                                if (matchingContactId == null) {
                                    doContactInsert(coreMgr, con, false, ci.contact, null, true, false);
                                } else {
                                    ci.contact.setContactId(matchingContactId);
                                    boolean updated = doContactUpdate(coreMgr, con, false, ci.contact, true,
                                            false);
                                    if (!updated)
                                        throw new WTException("Contact not found [{}]",
                                                ci.contact.getContactId());
                                }
                            }

                            hrefs.add(href); // Marks as processed!
                        }

                        if (syncByHref != null) { // Only if... (!full && !syncIsSupported) see above!
                            // Remaining hrefs -> deleted items
                            for (VContactHrefSync hrefSync : syncByHref.values()) {
                                logger.trace("Card deleted [{}]", hrefSync.getHref());
                                doContactDelete(con, hrefSync.getContactId(), false);
                            }
                        }

                        catDao.updateRemoteSyncById(con, categoryId, newLastSync, newSyncToken);
                        DbUtils.commitQuietly(con);

                    } catch (Exception ex) {
                        DbUtils.rollbackQuietly(con);
                        throw new WTException(ex, "Error importing vCard");
                    }
                }

            } catch (DavException ex) {
                throw new WTException(ex, "CardDAV error");
            }
        } else {
            throw new WTException("Unsupported provider [{0}]", cat.getProvider());
        }

    } catch (SQLException | DAOException ex) {
        throw wrapException(ex);
    } finally {
        DbUtils.closeQuietly(con);
        pendingRemoteCategorySyncs.remove(PENDING_KEY);
    }
}

From source file:com.android.messaging.datamodel.MessageNotificationState.java

/**
 * Check for failed messages and post notifications as needed.
 * TODO: Rewrite this as a NotificationState.
 *//*from  w ww . jav a 2 s .co  m*/
public static void checkFailedMessages() {
    final DatabaseWrapper db = DataModel.get().getDatabase();

    final Cursor messageDataCursor = db.query(DatabaseHelper.MESSAGES_TABLE, MessageData.getProjection(),
            FailedMessageQuery.FAILED_MESSAGES_WHERE_CLAUSE, null /*selectionArgs*/, null /*groupBy*/,
            null /*having*/, FailedMessageQuery.FAILED_ORDER_BY);

    try {
        final Context context = Factory.get().getApplicationContext();
        final Resources resources = context.getResources();
        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        if (messageDataCursor != null) {
            final MessageData messageData = new MessageData();

            final HashSet<String> conversationsWithFailedMessages = new HashSet<String>();

            // track row ids in case we want to display something that requires this
            // information
            final ArrayList<Integer> failedMessages = new ArrayList<Integer>();

            int cursorPosition = -1;
            final long when = 0;

            messageDataCursor.moveToPosition(-1);
            while (messageDataCursor.moveToNext()) {
                messageData.bind(messageDataCursor);

                final String conversationId = messageData.getConversationId();
                if (DataModel.get().isNewMessageObservable(conversationId)) {
                    // Don't post a system notification for an observable conversation
                    // because we already show an angry red annotation in the conversation
                    // itself or in the conversation preview snippet.
                    continue;
                }

                cursorPosition = messageDataCursor.getPosition();
                failedMessages.add(cursorPosition);
                conversationsWithFailedMessages.add(conversationId);
            }

            if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
                LogUtil.d(TAG, "Found " + failedMessages.size() + " failed messages");
            }
            if (failedMessages.size() > 0) {
                final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

                CharSequence line1;
                CharSequence line2;
                final boolean isRichContent = false;
                ConversationIdSet conversationIds = null;
                PendingIntent destinationIntent;
                if (failedMessages.size() == 1) {
                    messageDataCursor.moveToPosition(cursorPosition);
                    messageData.bind(messageDataCursor);
                    final String conversationId = messageData.getConversationId();

                    // We have a single conversation, go directly to that conversation.
                    destinationIntent = UIIntents.get().getPendingIntentForConversationActivity(context,
                            conversationId, null /*draft*/);

                    conversationIds = ConversationIdSet.createSet(conversationId);

                    final String failedMessgeSnippet = messageData.getMessageText();
                    int failureStringId;
                    if (messageData.getStatus() == MessageData.BUGLE_STATUS_INCOMING_DOWNLOAD_FAILED) {
                        failureStringId = R.string.notification_download_failures_line1_singular;
                    } else {
                        failureStringId = R.string.notification_send_failures_line1_singular;
                    }
                    line1 = resources.getString(failureStringId);
                    line2 = failedMessgeSnippet;
                    // Set rich text for non-SMS messages or MMS push notification messages
                    // which we generate locally with rich text
                    // TODO- fix this
                    //                        if (messageData.isMmsInd()) {
                    //                            isRichContent = true;
                    //                        }
                } else {
                    // We have notifications for multiple conversation, go to the conversation
                    // list.
                    destinationIntent = UIIntents.get().getPendingIntentForConversationListActivity(context);

                    int line1StringId;
                    int line2PluralsId;
                    if (messageData.getStatus() == MessageData.BUGLE_STATUS_INCOMING_DOWNLOAD_FAILED) {
                        line1StringId = R.string.notification_download_failures_line1_plural;
                        line2PluralsId = R.plurals.notification_download_failures;
                    } else {
                        line1StringId = R.string.notification_send_failures_line1_plural;
                        line2PluralsId = R.plurals.notification_send_failures;
                    }
                    line1 = resources.getString(line1StringId);
                    line2 = resources.getQuantityString(line2PluralsId, conversationsWithFailedMessages.size(),
                            failedMessages.size(), conversationsWithFailedMessages.size());
                }
                line1 = applyWarningTextColor(context, line1);
                line2 = applyWarningTextColor(context, line2);

                final PendingIntent pendingIntentForDelete = UIIntents.get()
                        .getPendingIntentForClearingNotifications(context, BugleNotifications.UPDATE_ERRORS,
                                conversationIds, 0);

                builder.setContentTitle(line1).setTicker(line1)
                        .setWhen(when > 0 ? when : System.currentTimeMillis())
                        .setSmallIcon(R.drawable.ic_failed_light).setDeleteIntent(pendingIntentForDelete)
                        .setContentIntent(destinationIntent)
                        .setSound(UriUtil.getUriForResourceId(context, R.raw.message_failure));
                if (isRichContent && !TextUtils.isEmpty(line2)) {
                    final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
                    if (line2 != null) {
                        inboxStyle.addLine(Html.fromHtml(line2.toString()));
                    }
                    builder.setStyle(inboxStyle);
                } else {
                    builder.setContentText(line2);
                }

                if (builder != null) {
                    notificationManager.notify(BugleNotifications
                            .buildNotificationTag(PendingIntentConstants.MSG_SEND_ERROR, null),
                            PendingIntentConstants.MSG_SEND_ERROR, builder.build());
                }
            } else {
                notificationManager.cancel(
                        BugleNotifications.buildNotificationTag(PendingIntentConstants.MSG_SEND_ERROR, null),
                        PendingIntentConstants.MSG_SEND_ERROR);
            }
        }
    } finally {
        if (messageDataCursor != null) {
            messageDataCursor.close();
        }
    }
}

From source file:com.gemstone.gemfire.internal.cache.OplogJUnitTest.java

private void verifyOplogHeader(File dir, String... oplogTypes) throws IOException {

    Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> {
        List<String> types = new ArrayList<>(Arrays.asList(oplogTypes));
        Arrays.stream(dir.listFiles()).map(File::getName).map(f -> f.substring(f.indexOf(".")))
                .forEach(types::remove);
        return types.isEmpty();
    });/*from   w w w . j  a  v a 2 s.com*/

    File[] files = dir.listFiles();
    HashSet<String> verified = new HashSet<String>();
    for (File file : files) {
        String name = file.getName();
        byte[] expect = new byte[Oplog.OPLOG_MAGIC_SEQ_REC_SIZE];
        if (name.endsWith(".crf")) {
            expect[0] = Oplog.OPLOG_MAGIC_SEQ_ID;
            System.arraycopy(OPLOG_TYPE.CRF.getBytes(), 0, expect, 1, OPLOG_TYPE.getLen());
            verified.add(".crf");
        } else if (name.endsWith(".drf")) {
            expect[0] = Oplog.OPLOG_MAGIC_SEQ_ID;
            System.arraycopy(OPLOG_TYPE.DRF.getBytes(), 0, expect, 1, OPLOG_TYPE.getLen());
            verified.add(".drf");
        } else if (name.endsWith(".krf")) {
            expect[0] = Oplog.OPLOG_MAGIC_SEQ_ID;
            System.arraycopy(OPLOG_TYPE.KRF.getBytes(), 0, expect, 1, OPLOG_TYPE.getLen());
            verified.add(".krf");
        } else if (name.endsWith(".if")) {
            expect[0] = DiskInitFile.OPLOG_MAGIC_SEQ_ID;
            System.arraycopy(OPLOG_TYPE.IF.getBytes(), 0, expect, 1, OPLOG_TYPE.getLen());
            verified.add(".if");
        } else {
            System.out.println("Ignored: " + file);
            continue;
        }
        expect[expect.length - 1] = 21; // EndOfRecord

        byte[] buf = new byte[Oplog.OPLOG_MAGIC_SEQ_REC_SIZE];

        FileInputStream fis = new FileInputStream(file);
        int count = fis.read(buf, 0, 8);
        fis.close();

        System.out.println("Verifying: " + file);
        assertEquals("expected a read to return 8 but it returned " + count + " for file " + file, 8, count);
        assertTrue(Arrays.equals(expect, buf));
    }

    assertEquals(oplogTypes.length, verified.size());
}

From source file:org.roaringbitmap.TestRoaringBitmap.java

@Test
public void ortest3() {
    final HashSet<Integer> V1 = new HashSet<Integer>();
    final HashSet<Integer> V2 = new HashSet<Integer>();

    final RoaringBitmap rr = new RoaringBitmap();
    final RoaringBitmap rr2 = new RoaringBitmap();
    // For the first 65536: rr2 has a bitmap container, and rr has
    // an array container.
    // We will check the union between a BitmapCintainer and an
    // arrayContainer
    for (int k = 0; k < 4000; ++k) {
        rr2.add(k);/*from   w w  w  .j  a  v  a 2  s . co  m*/
        V1.add(k);
    }
    for (int k = 3500; k < 4500; ++k) {
        rr.add(k);
        V1.add(k);
    }
    for (int k = 4000; k < 65000; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    // In the second node of each roaring bitmap, we have two bitmap
    // containers.
    // So, we will check the union between two BitmapContainers
    for (int k = 65536; k < 65536 + 10000; ++k) {
        rr.add(k);
        V1.add(k);
    }

    for (int k = 65536; k < 65536 + 14000; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    // In the 3rd node of each Roaring Bitmap, we have an
    // ArrayContainer, so, we will try the union between two
    // ArrayContainers.
    for (int k = 4 * 65535; k < 4 * 65535 + 1000; ++k) {
        rr.add(k);
        V1.add(k);
    }

    for (int k = 4 * 65535; k < 4 * 65535 + 800; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    // For the rest, we will check if the union will take them in
    // the result
    for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) {
        rr.add(k);
        V1.add(k);
    }

    for (int k = 7 * 65535; k < 7 * 65535 + 2000; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    final RoaringBitmap rror = RoaringBitmap.or(rr, rr2);
    boolean valide = true;

    // Si tous les elements de rror sont dans V1 et que tous les
    // elements de
    // V1 sont dans rror(V2)
    // alors V1 == rror

    final Object[] tab = V1.toArray();
    final Vector<Integer> vector = new Vector<Integer>();
    for (Object aTab : tab)
        vector.add((Integer) aTab);

    for (final int i : rror.toArray()) {
        if (!vector.contains(new Integer(i))) {
            valide = false;
        }
        V2.add(i);
    }
    for (int i = 0; i < V1.size(); i++)
        if (!V2.contains(vector.elementAt(i))) {
            valide = false;
        }

    Assert.assertEquals(valide, true);
}

From source file:org.roaringbitmap.TestRoaringBitmap.java

@Test
public void xortest1() {
    final HashSet<Integer> V1 = new HashSet<Integer>();
    final HashSet<Integer> V2 = new HashSet<Integer>();

    final RoaringBitmap rr = new RoaringBitmap();
    final RoaringBitmap rr2 = new RoaringBitmap();
    // For the first 65536: rr2 has a bitmap container, and rr has
    // an array container.
    // We will check the union between a BitmapCintainer and an
    // arrayContainer
    for (int k = 0; k < 4000; ++k) {
        rr2.add(k);/*from   ww  w  .ja  va  2 s  . com*/
        if (k < 3500)
            V1.add(k);
    }
    for (int k = 3500; k < 4500; ++k) {
        rr.add(k);
    }
    for (int k = 4000; k < 65000; ++k) {
        rr2.add(k);
        if (k >= 4500)
            V1.add(k);
    }

    // In the second node of each roaring bitmap, we have two bitmap
    // containers.
    // So, we will check the union between two BitmapContainers
    for (int k = 65536; k < 65536 + 30000; ++k) {
        rr.add(k);
    }

    for (int k = 65536; k < 65536 + 50000; ++k) {
        rr2.add(k);
        if (k >= 65536 + 30000)
            V1.add(k);
    }

    // In the 3rd node of each Roaring Bitmap, we have an
    // ArrayContainer. So, we will try the union between two
    // ArrayContainers.
    for (int k = 4 * 65535; k < 4 * 65535 + 1000; ++k) {
        rr.add(k);
        if (k >= 4 * 65535 + 800)
            V1.add(k);
    }

    for (int k = 4 * 65535; k < 4 * 65535 + 800; ++k) {
        rr2.add(k);
    }

    // For the rest, we will check if the union will take them in
    // the result
    for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) {
        rr.add(k);
        V1.add(k);
    }

    for (int k = 7 * 65535; k < 7 * 65535 + 2000; ++k) {
        rr2.add(k);
        V1.add(k);
    }

    final RoaringBitmap rrxor = RoaringBitmap.xor(rr, rr2);
    boolean valide = true;

    // Si tous les elements de rror sont dans V1 et que tous les
    // elements de
    // V1 sont dans rror(V2)
    // alors V1 == rror
    final Object[] tab = V1.toArray();
    final Vector<Integer> vector = new Vector<Integer>();
    for (Object aTab : tab)
        vector.add((Integer) aTab);

    for (final int i : rrxor.toArray()) {
        if (!vector.contains(new Integer(i))) {
            valide = false;
        }
        V2.add(i);
    }
    for (int i = 0; i < V1.size(); i++)
        if (!V2.contains(vector.elementAt(i))) {
            valide = false;
        }

    Assert.assertEquals(valide, true);
}

From source file:org.apache.hadoop.hbase.client.TestFromClientSide.java

@Test
public void testListTables() throws IOException, InterruptedException {
    byte[] t1 = Bytes.toBytes("testListTables1");
    byte[] t2 = Bytes.toBytes("testListTables2");
    byte[] t3 = Bytes.toBytes("testListTables3");
    byte[][] tables = new byte[][] { t1, t2, t3 };
    for (int i = 0; i < tables.length; i++) {
        TEST_UTIL.createTable(tables[i], FAMILY);
    }/*from   w  w w.j  ava2s.co  m*/
    HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
    HTableDescriptor[] ts = admin.listTables();
    HashSet<HTableDescriptor> result = new HashSet<HTableDescriptor>(ts.length);
    for (int i = 0; i < ts.length; i++) {
        result.add(ts[i]);
    }
    int size = result.size();
    assertTrue(size >= tables.length);
    for (int i = 0; i < tables.length && i < size; i++) {
        boolean found = false;
        for (int j = 0; j < ts.length; j++) {
            if (Bytes.equals(ts[j].getTableName().getName(), tables[i])) {
                found = true;
                break;
            }
        }
        assertTrue("Not found: " + Bytes.toString(tables[i]), found);
    }
}

From source file:edu.ku.brc.af.ui.forms.FormViewObj.java

/**
 * @param rs/*from  ww w  .  j a  v a 2  s  . c o m*/
 * @param resultSet
 */
protected void countResultsBack(final RecordSetIFace rs, final java.sql.ResultSet resultSet) {
    try {
        if (resultSet.next()) {
            HashSet<Integer> availableIdList = new HashSet<Integer>();
            do {
                availableIdList.add(resultSet.getInt(1));

            } while (resultSet.next());

            if (availableIdList.size() != rs.getNumItems()) {
                UIRegistry.displayLocalizedStatusBarText("FormViewObj.NOT_ALL_RECS_FOUND");
            }

            if (recordSet == null) {
                recordSet = RecordSetFactory.getInstance().createRecordSet();
            }

            recordSetItemList = new Vector<RecordSetItemIFace>(availableIdList.size());
            for (RecordSetItemIFace rsi : rs.getOrderedItems()) {
                if (availableIdList.contains(rsi.getRecordId())) {
                    recordSetItemList.add(rsi);
                    recordSet.addItem(rsi);
                }
            }
            Object firstDataObj = getDataObjectViaRecordSet(0);
            Vector<Object> tmpList = new Vector<Object>(availableIdList.size() + 5);
            tmpList.add(firstDataObj);
            for (int i = 1; i < recordSetItemList.size(); i++) {
                tmpList.add(null);
            }

            if (mvParent != null) {
                mvParent.setData(tmpList);
                mvParent.setRecordSetItemList(this, tableInfo, recordSetItemList);

            } else {
                setDataObj(tmpList);
            }

        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                            getResourceString("NO_RECORD_FOUND"), getResourceString("NO_RECORD_FOUND_TITLE"),
                            JOptionPane.WARNING_MESSAGE);
                }
            });
        }
    } catch (SQLException ex) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                        getResourceString("ERROR_LOADING_FORM_DATA"),
                        getResourceString("ERROR_LOADING_FORM_DATA_TITLE"), JOptionPane.WARNING_MESSAGE);
            }
        });
    }

}