Example usage for java.lang Integer compareTo

List of usage examples for java.lang Integer compareTo

Introduction

In this page you can find the example usage for java.lang Integer compareTo.

Prototype

public int compareTo(Integer anotherInteger) 

Source Link

Document

Compares two Integer objects numerically.

Usage

From source file:org.jahia.utils.maven.plugin.contentgenerator.UserGroupService.java

public List<UserBO> generateUsers(Integer nbUsers, Integer nbCollectionsPerUser, Integer nbFilesPerCollection,
        Integer nbFilesGenerated) {
    logger.info(nbUsers + " users are going to be generated");

    List<UserBO> users = new ArrayList<UserBO>();
    for (int userid = 0; userid < nbUsers; userid++) {

        String username = "user" + userid;
        String pathJcr = getPathForUsername(username);

        List<CollectionBO> collections = new ArrayList<CollectionBO>();
        if (nbCollectionsPerUser != null && nbCollectionsPerUser.compareTo(0) > 0) {
            CollectionService collectionService = CollectionService.getInstance();
            collections = collectionService.generateCollections(nbCollectionsPerUser, nbFilesPerCollection,
                    nbFilesGenerated, username);
        }/*from w  w w  . j  a  v  a  2  s  . c  o  m*/

        UserBO user = new UserBO(username, JahiaGlobalConfigurator.encryptPassword(username), pathJcr,
                collections);
        users.add(user);
    }
    return users;
}

From source file:net.sourceforge.subsonic.domain.Playlist.java

/**
 * Sorts the playlist according to the given sort order.
 *///from w ww  . j av  a  2s .com
public synchronized void sort(final SortOrder sortOrder) {
    makeBackup();
    MediaFile currentFile = getCurrentFile();

    Comparator<MediaFile> comparator = new Comparator<MediaFile>() {
        public int compare(MediaFile a, MediaFile b) {
            switch (sortOrder) {
            case TRACK:
                Integer trackA = a.getTrackNumber();
                Integer trackB = b.getTrackNumber();
                if (trackA == null) {
                    trackA = 0;
                }
                if (trackB == null) {
                    trackB = 0;
                }
                return trackA.compareTo(trackB);

            case ARTIST:
                String artistA = StringUtils.trimToEmpty(a.getArtist());
                String artistB = StringUtils.trimToEmpty(b.getArtist());
                return artistA.compareTo(artistB);

            case ALBUM:
                String albumA = StringUtils.trimToEmpty(a.getAlbumName());
                String albumB = StringUtils.trimToEmpty(b.getAlbumName());
                return albumA.compareTo(albumB);
            default:
                return 0;
            }
        }
    };

    Collections.sort(files, comparator);
    if (currentFile != null) {
        index = files.indexOf(currentFile);
    }
}

From source file:org.gbif.portal.webservices.actions.DensityAction.java

@SuppressWarnings("unchecked")
public Map<String, Object> findDensityRecords(DensityParameters params) throws GbifWebServiceException {

    Map<String, Object> results = new HashMap<String, Object>();

    Map<String, String> headerMap;
    Map<String, String> parameterMap;
    Map<String, String> summaryMap = null;

    headerMap = returnHeader(params, true);
    parameterMap = returnParameters(params.getParameterMap(null));

    List<CellDensityDTO> densities = null;

    try {//from  w  w w .  j a  v  a  2 s .c  o  m

        String key = params.getKey();
        if (params.getEntityType() == EntityType.TYPE_COUNTRY) {
            try {
                CountryDTO country = geospatialManager.getCountryForIsoCountryCode(key, Locale.ENGLISH);
                if (country != null) {
                    key = country.getKey();
                }
            } catch (Exception e) {
                key = null;
            }
        }

        if (params.getEntityType() == EntityType.TYPE_DEPARTMENT) {
            try {
                DepartmentDTO department = departmentManager.getDepartmentForIsoDepartmentCode(key);
                if (department != null) {
                    key = department.getKey();
                }
            } catch (Exception e) {
                key = null;
                log.debug("department null");
            }
        }

        if (key != null) {
            densities = geospatialManager.get1DegCellDensities(params.getEntityType(), key);
        } else {
            densities = new ArrayList<CellDensityDTO>();
        }

        summaryMap = returnSummary(params, densities, false);

        List<Map<String, String>> cellDensityMapList = new LinkedList<Map<String, String>>();
        Map<String, String> cellDensityMap = null;

        //request is of KML format
        if (params.getFormat() == DensityParameters.FORMAT_KML) {
            String name = "GBIF Data Portal Occurrence Density Layer";
            String shortName = "Density Layer";

            //just customize the name for the KML document
            if (params.getEntityType() == EntityType.TYPE_COUNTRY) {
                shortName = params.getKey();
                name += " for country " + shortName;
            } else if (params.getEntityType() == EntityType.TYPE_DEPARTMENT) {
                shortName = params.getKey();
                name += " for department " + shortName;
            } else if (params.getEntityType() == EntityType.TYPE_DATA_PROVIDER) {
                DataProviderDTO provider = dataResourceManager.getDataProviderFor(params.getKey());
                shortName = provider.getName();
                name += " for data provider: " + shortName;
            } else if (params.getEntityType() == EntityType.TYPE_DATA_RESOURCE) {
                DataResourceDTO resource = dataResourceManager.getDataResourceFor(params.getKey());
                shortName = resource.getName();
                name += " for data resource: " + shortName + " from data provider: "
                        + resource.getDataProviderName();
            } else if (params.getEntityType() == EntityType.TYPE_RESOURCE_NETWORK) {
                ResourceNetworkDTO network = dataResourceManager.getResourceNetworkFor(params.getKey());
                shortName = network.getName();
                name += " for resource network: " + shortName;
            } else if (params.getEntityType() == EntityType.TYPE_TAXON) {
                TaxonConceptDTO taxon = taxonomyManager.getTaxonConceptFor(params.getKey());
                shortName = taxon.getTaxonName();
                name += " for " + taxon.getRank() + ": " + shortName;
            }

            //iterate over all the CellDensityDTOs and create a Map per each one
            for (CellDensityDTO dto : densities) {

                cellDensityMap = new TreeMap<String, String>();

                //bounding box
                LatLongBoundingBox bbox = CellIdUtils.toBoundingBox(dto.getCellId());
                //folder name
                String folderName = new Integer(dto.getCount()).toString() + " record"
                        + (dto.getCount() > 1 ? "s" : "");
                //placemark attributes
                String placemarkName = shortName + " - " + folderName;
                String placemarkVisibility = "false";
                String placemarkDescription = "<p><img src=\"" + params.getPortalRoot()
                        + "/images/gbifSmall.gif\"/></p><p><a href=\""
                        + getCellOccurrenceURL(params, dto, false) + "\">Download</a></p>";
                String placemarkStyleUrl = "#downArrowIcon";
                String placemarkPointCoordinates = new Double((bbox.getMinLong() + bbox.getMaxLong()) / 2)
                        .toString() + "," + new Double((bbox.getMinLat() + bbox.getMaxLat()) / 2).toString()
                        + ",0";
                //ground overlay attributes
                String groundOverlayVisibility = "true";
                String groundOverlayColor = getDensityColour(dto.getCount());
                String groundOverlayBoxNorth = new Float(bbox.getMaxLat()).toString();
                String groundOverlayBoxSouth = new Float(bbox.getMinLat()).toString();
                String groundOverlayBoxEast = new Float(bbox.getMaxLong()).toString();
                String groundOverlayBoxWest = new Float(bbox.getMinLong()).toString();

                //fill in the map
                cellDensityMap.put("folderName", folderName);
                cellDensityMap.put("placemarkName", placemarkName);
                cellDensityMap.put("placemarkVisibility", placemarkVisibility);
                cellDensityMap.put("placemarkDescription", placemarkDescription);
                cellDensityMap.put("placemarkStyleUrl", placemarkStyleUrl);
                cellDensityMap.put("placemarkPointCoordinates", placemarkPointCoordinates);
                cellDensityMap.put("groundOverlayVisibility", groundOverlayVisibility);
                cellDensityMap.put("groundOverlayColor", groundOverlayColor);
                cellDensityMap.put("groundOverlayBoxNorth", groundOverlayBoxNorth);
                cellDensityMap.put("groundOverlayBoxSouth", groundOverlayBoxSouth);
                cellDensityMap.put("groundOverlayBoxEast", groundOverlayBoxEast);
                cellDensityMap.put("groundOverlayBoxWest", groundOverlayBoxWest);

                cellDensityMapList.add(cellDensityMap);
            }

            //Attributes for the Map being passed to the Velocity template
            results.put("documentName", name);
            results.put("documentOpen", "true");
            results.put("documentDescription", params.getStatements());

            results.put("documentStyleId", "downArrowIcon");
            results.put("documentStyleIconHref", "http://maps.google.com/mapfiles/kml/pal4/icon28.png");

            results.put("results", cellDensityMapList);
        } else //request is of standard format
        {
            String schemaLocation = params.getSchemaLocation();
            //iterate over all the CellDensityDTOs a create a Map per each one
            for (CellDensityDTO dto : densities) {
                cellDensityMap = new HashMap<String, String>();

                //bounding box
                LatLongBoundingBox bbox = CellIdUtils.toBoundingBox(dto.getCellId());

                //Density record attributes
                String cellId = new Integer(dto.getCellId()).toString();
                String count = new Integer(dto.getCount()).toString();
                String portalUrl = getCellOccurrenceURL(params, dto, true);
                String minLatitude = new Float(bbox.getMinLat()).toString();
                String maxLatitude = new Float(bbox.getMaxLat()).toString();
                String minLongitude = new Float(bbox.getMinLong()).toString();
                String maxLongitude = new Float(bbox.getMaxLong()).toString();

                //fill the map
                cellDensityMap.put("cellId", cellId);
                cellDensityMap.put("count", count);
                cellDensityMap.put("portalUrl", portalUrl);
                cellDensityMap.put("minLatitude", minLatitude);
                cellDensityMap.put("maxLatitude", maxLatitude);
                cellDensityMap.put("minLongitude", minLongitude);
                cellDensityMap.put("maxLongitude", maxLongitude);

                cellDensityMapList.add(cellDensityMap);
            }

            //order all the cell density records by their CELL ID (descending order)
            Collections.sort(cellDensityMapList, new Comparator() {
                public int compare(Object a, Object b) {
                    Map cellDensity1 = (Map) a;
                    Map cellDensity2 = (Map) b;
                    Integer key1 = Integer.parseInt(cellDensity1.get("cellId").toString());
                    Integer key2 = Integer.parseInt(cellDensity2.get("cellId").toString());
                    return key1.compareTo(key2);
                }
            });

            results.put("results", cellDensityMapList);

            results.put("summaryStart", new BigInteger(new Integer(params.getStartIndex()).toString()));
            results.put("summaryTotalMatched",
                    new BigInteger(new Integer(params.getStartIndex() + densities.size()).toString()));
            results.put("summaryTotalReturned", new BigInteger(new Integer(densities.size()).toString()));
        }

        results.put("headerMap", headerMap);
        results.put("parameterMap", parameterMap);
        results.put("summaryMap", summaryMap);

        results.put("count", densities.size());

        return results;

    } catch (ServiceException se) {
        log.error("Unregistered data service error: " + se.getMessage(), se);
        throw new GbifWebServiceException("Data service problems - " + se.getMessage());
    } catch (Exception se) {
        log.error("Data service error: " + se.getMessage(), se);
        throw new GbifWebServiceException("Data service problems - " + se.toString());
    }

}

From source file:org.kuali.kpme.core.paystep.PayStepBo.java

@Override
public int compareTo(Object o) {
    if (o instanceof PayStepBo) {
        PayStepBo s = (PayStepBo) o;//  w w  w. ja va 2  s . c  om
        if (StringUtils.equals(s.salaryGroup, salaryGroup) && StringUtils.equals(s.payGrade, payGrade)) {

            Integer otherServiceTime = 0;
            if (StringUtils.equals(s.serviceUnit, HrConstants.SERVICE_TIME_YEAR))
                otherServiceTime = s.getServiceAmount() * 12;
            else
                otherServiceTime = s.getServiceAmount();

            Integer thisServiceTime = 0;
            if (StringUtils.equals(serviceUnit, HrConstants.SERVICE_TIME_YEAR))
                thisServiceTime = serviceAmount * 12;
            else
                thisServiceTime = serviceAmount;

            return otherServiceTime.compareTo(thisServiceTime);
        } else
            //   throw new IllegalArgumentException("pay step must be within the same salary group and pay grade");
            LOG.error("pay step must be within the same salary group and pay grade");
    }

    return 0;
}

From source file:org.opendatakit.aggregate.parser.NamingSet.java

/**
 * Resolve the column names in each table definition so they are unique within
 * that table.// w w  w.  j ava  2 s  . co  m
 *
 * @param maxLenColumnName
 */
private void resolveColumnNames(int maxLenColumnName) {
    try {
        // resolve the column names within a table
        for (Map.Entry<String, Map<String, Name>> colMap : columnPlaceholders.entrySet()) {
            // We have the column map entry for a given table.

            // now, construct a map of qualifier -to- max item name length
            // for each different qualifier of column names.
            Map<String, Integer> qualMaxName = new TreeMap<String, Integer>();
            for (Map.Entry<String, Name> col : colMap.getValue().entrySet()) {
                int len = col.getValue().itemName.length();
                String qualifier = col.getValue().qualifier;
                Integer curMax = qualMaxName.get(qualifier);
                if (curMax == null || curMax.compareTo(len) < 0) {
                    qualMaxName.put(qualifier, len);
                }
            }

            // and go through the columns in the table creating consistently
            // munged column names by shrinking the qualifier a consistent
            // amount across all the fields it qualifies.
            for (Map.Entry<String, Name> col : colMap.getValue().entrySet()) {
                Name nm = col.getValue();
                String qualifier = nm.qualifier;
                int maxAll = qualMaxName.get(qualifier);
                // remainder available to the qualifier... (extra one is for '_')
                int remainder = maxLenColumnName - maxAll - 1;
                if (qualifier.length() == 0) {
                    // truncate the item name, since it is all we have...
                    nm.mungedQualifier = nm.qualifier;
                    nm.mungedItemName = trimName(nm.itemName, maxLenColumnName);
                } else if (qualifier.length() <= remainder) {
                    // (qualifier + max item name) is short enough to avoid truncation
                    nm.mungedQualifier = nm.qualifier;
                    nm.mungedItemName = nm.itemName;
                } else if ((remainder >= 3) && (qualifier.length() <= 11
                        || remainder >= Integer.toString(qualifier.length() - 2).length() + 2)) {
                    // truncate qualifier to remainder...
                    // In the worst case, we have enough room
                    // to encode the qualifier with an I18N style encoding.
                    nm.mungedQualifier = trimName(nm.qualifier, remainder);
                    nm.mungedItemName = nm.itemName;
                } else {
                    // we have to pare down both the qualifier and the item name.
                    // trim the qualifier to be 1/3 the max length, and the
                    // item name to be 2/3 the max length...
                    remainder = maxLenColumnName / 3;
                    nm.mungedQualifier = trimName(nm.qualifier, remainder - 1);
                    nm.mungedItemName = trimName(nm.itemName, maxLenColumnName - remainder);
                }

                if (nm.mungedQualifier.length() == 0) {
                    nm.resolvedName = nm.mungedItemName;
                } else {
                    nm.resolvedName = nm.mungedQualifier + "_" + nm.mungedItemName;
                }

                if (nm.resolvedName.length() > maxLenColumnName) {
                    logger.error("Munged resolved name still too long: " + nm.resolvedName);
                    nm.resolvedName = trimName(nm.resolvedName, maxLenColumnName);
                }
            }

            // we now have the set of candidate resolved names.
            // build a set of these to ensure no collisions. If we find a collision,
            // resolve by appending suffix count and re-trimming as needed.
            Set<String> resolvedNames = new TreeSet<String>();
            for (Map.Entry<String, Name> col : colMap.getValue().entrySet()) {
                Name nm = col.getValue();
                if (resolvedNames.contains(nm.resolvedName)) {
                    // collision
                    int dupCounter = 2;
                    String newName = trimName(nm.resolvedName + Integer.toString(dupCounter++),
                            maxLenColumnName);
                    while (resolvedNames.contains(newName)) {
                        newName = trimName(nm.resolvedName + Integer.toString(dupCounter++), maxLenColumnName);
                    }
                    nm.resolvedName = newName;
                }
                resolvedNames.add(nm.resolvedName);
            }
            // OK. At this point, we have found good column names for this table!
        }
    } catch (IndexOutOfBoundsException e) {
        logger.error("Index out of bounds exception");
        dumpTablesInternal("idxOutOfBounds", 0, true);
        throw e;
    }
}

From source file:fr.hoteia.qalingo.core.domain.CatalogCategoryVirtual.java

public List<CatalogCategoryVirtual> getCatalogCategories(final Long marketAreaId) {
    List<CatalogCategoryVirtual> sortedObjects = new LinkedList<CatalogCategoryVirtual>(catalogCategories);
    Collections.sort(sortedObjects, new Comparator<CatalogCategoryVirtual>() {
        @Override/*from  w  ww  .  j a v a 2s . c om*/
        public int compare(CatalogCategoryVirtual o1, CatalogCategoryVirtual o2) {
            if (o1 != null && o2 != null) {
                Integer order1 = o1.getOrder(marketAreaId);
                Integer order2 = o2.getOrder(marketAreaId);
                if (order1 != null && order2 != null) {
                    return order1.compareTo(order2);
                } else {
                    return o1.getId().compareTo(o2.getId());
                }
            }
            return 0;
        }
    });
    return sortedObjects;
}

From source file:org.nuclos.server.masterdata.valueobject.MasterDataMetaVO.java

/**
 * get all fields for master data meta record
 * @return sorted list of fields//from   w ww  .  j  a  va  2 s.c  om
 */
public List<MasterDataMetaFieldVO> getFields() {
    final List<MasterDataMetaFieldVO> result = new ArrayList<MasterDataMetaFieldVO>(mpFields.values());
    Collections.sort(result, new Comparator<MasterDataMetaFieldVO>() {
        @Override
        public int compare(MasterDataMetaFieldVO vo1, MasterDataMetaFieldVO vo2) {
            Integer i1 = new Integer(0);
            Integer i2 = new Integer(0);
            if (vo1.getId() != null) {
                i1 = new Integer(vo1.getId());
            }
            if (vo2.getId() != null) {
                i2 = new Integer(vo2.getId());
            }
            return i1.compareTo(i2);
        }
    });
    return result;
}

From source file:org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceOrder.java

public ElectronicInvoiceItem getElectronicInvoiceItemByPOLineNumber(Integer poLineNumber) {
    for (Iterator iter = this.invoiceItems.iterator(); iter.hasNext();) {
        ElectronicInvoiceItem eii = (ElectronicInvoiceItem) iter.next();
        if ((poLineNumber.compareTo(eii.getReferenceLineNumberInteger())) == 0) {
            return eii;
        }/*  w  w  w  . j  av  a  2  s .c  o  m*/
    }
    return null;
}

From source file:com.manydesigns.portofino.sync.DatabaseSyncer.java

protected void syncColumns(final liquibase.database.structure.Table liquibaseTable, final Table sourceTable,
        final Table targetTable) {
    logger.debug("Synchronizing columns");
    for (liquibase.database.structure.Column liquibaseColumn : liquibaseTable.getColumns()) {
        logger.debug("Processing column: {}", liquibaseColumn.getName());

        Column targetColumn = new Column(targetTable);

        targetColumn.setColumnName(liquibaseColumn.getName());
        // hongliangpan add
        targetColumn.setMemo(liquibaseColumn.getRemarks());

        logger.debug("Merging column attributes and annotations");
        targetColumn.setAutoincrement(liquibaseColumn.isAutoIncrement());
        int jdbcType = liquibaseColumn.getDataType();
        if (jdbcType == Types.OTHER) {
            logger.debug("jdbcType = OTHER, trying to determine more specific type from type name");
            String jdbcTypeName = liquibaseColumn.getTypeName();
            try {
                Field field = Types.class.getField(jdbcTypeName);
                jdbcType = (Integer) field.get(null);
            } catch (Exception e) {
                logger.debug("Could not determine type (type name = {})", jdbcTypeName);
            }//from www . ja  v  a 2s .com
        }
        targetColumn.setJdbcType(jdbcType);
        targetColumn.setColumnType(liquibaseColumn.getTypeName());
        targetColumn.setLength(liquibaseColumn.getColumnSize());

        targetColumn.setNullable(liquibaseColumn.isNullable());
        targetColumn.setScale(liquibaseColumn.getDecimalDigits());
        // TODO liquibaseColumn.getLengthSemantics()

        Column sourceColumn = DatabaseLogic.findColumnByNameIgnoreCase(sourceTable, liquibaseColumn.getName());
        if (sourceColumn != null) {
            targetColumn.setPropertyName(sourceColumn.getPropertyName());
            targetColumn.setJavaType(sourceColumn.getJavaType());
            copyAnnotations(sourceColumn, targetColumn);
            // hongliangpan add
            targetColumn.setNullable(sourceColumn.isNullable());
        }
        // hongliangpan add
        if (targetColumn.getColumnName().startsWith("c_is_")) {
            targetColumn.setJavaType(Boolean.class.getName());
        }

        // "TIMESTAMP"?hongliangpan add
        if ("TIMESTAMP".equals(liquibaseColumn.getTypeName())
                || "DATETIME".equals(liquibaseColumn.getTypeName())) {
            targetColumn.setNullable(true);
            addAnnotation(targetColumn, "com.manydesigns.elements.annotations.DateFormat",
                    "yyyy-MM-dd HH:mm:ss");
        }
        logger.debug("Column creation successfull. Adding column to table.");
        targetTable.getColumns().add(targetColumn);
    }

    logger.debug("Sorting columns to preserve their previous order as much as possible");
    Collections.sort(targetTable.getColumns(), new Comparator<Column>() {
        private int oldIndex(final Column c) {
            int i = 0;
            for (Column old : sourceTable.getColumns()) {
                if (old.getColumnName().equals(c.getColumnName())) {
                    return i;
                }
                i++;
            }
            return -1;
        }

        @Override
        public int compare(final Column c1, final Column c2) {
            Integer index1 = oldIndex(c1);
            Integer index2 = oldIndex(c2);
            if (index1 != -1) {
                if (index2 != -1) {
                    return index1.compareTo(index2);
                } else {
                    return -1;
                }
            } else {
                return index2 == -1 ? 0 : 1;
            }
        }
    });
}

From source file:org.opendatakit.aggregate.parser.NamingSet.java

/**
 * Resolve the table names. This requires asking the persistence layer if the
 * table already exists. We are creating tables for a new form, so it should
 * not stomp on any existing tables./*from  w w w .j  av  a  2s .  co m*/
 *
 * @param ds
 * @param user
 * @throws ODKDatastoreException
 */
private void resolveTableNames(Datastore ds, User user) throws ODKDatastoreException {
    int maxLenTableName = ds.getMaxLenTableName();
    // resolve the table names

    // construct a map of qualifier -to- max item name length
    // for each different qualifier of table names.
    int maxTblPrefix = 0;
    int maxQualLen = 0;
    int maxItemName = 0;
    Map<String, Integer> qualMaxName = new TreeMap<String, Integer>();
    for (Map.Entry<String, Name> tbl : tablePlaceholders.entrySet()) {
        Name nm = tbl.getValue();
        int len = nm.itemName.length();
        String qualifier = nm.qualifier;
        Integer curMax = qualMaxName.get(qualifier);
        if (curMax == null || curMax.compareTo(len) < 0) {
            qualMaxName.put(qualifier, len);
        }
        if (len > maxItemName) {
            maxItemName = len;
        }
        if (qualifier.length() > maxQualLen) {
            maxQualLen = qualifier.length();
        }
        if (nm.prefix.length() > maxTblPrefix) {
            maxTblPrefix = nm.prefix.length();
        }
    }

    int fixTblPrefixLen = maxTblPrefix;
    int fixTblQualLen = maxQualLen;
    int dashCount = 0;
    if (fixTblPrefixLen > 0)
        ++dashCount;
    if (fixTblQualLen > 0)
        ++dashCount;
    int fixTblItemLen = maxLenTableName - fixTblPrefixLen - fixTblQualLen - dashCount;

    if (maxTblPrefix + maxQualLen + maxItemName + dashCount > maxLenTableName
            && maxTblPrefix + maxQualLen + dashCount > (2 * maxLenTableName) / 5) {
        // clip the table prefix and qualifier lengths so that
        // the item name can be 60% of the resolved table name.

        // determine the space allocated to the item name...
        fixTblItemLen = (3 * maxLenTableName) / 5; // 60%...
        if (fixTblItemLen > maxItemName) {
            // the actual item names are shorter than this -- adjust down...
            fixTblItemLen = maxItemName;
        }

        int remainder = maxLenTableName - fixTblItemLen;

        fixTblPrefixLen = remainder / 3;
        if (fixTblPrefixLen > maxTblPrefix) {
            // the table prefix is smaller -- adjust down...
            fixTblPrefixLen = maxTblPrefix;
        }

        fixTblQualLen = remainder - fixTblPrefixLen;

        // and shorten the qualifier and table prefix to make room for '_'s
        if (fixTblQualLen > 0) {
            if (fixTblQualLen == 1) {
                fixTblPrefixLen--;
            } else {
                fixTblQualLen--;
            }
        }
        if (fixTblPrefixLen > 0) {
            if (fixTblPrefixLen == 1) {
                fixTblQualLen--;
            } else {
                fixTblPrefixLen--;
            }
        }
    }

    if (fixTblPrefixLen + fixTblQualLen + fixTblItemLen + dashCount > maxLenTableName) {
        throw new IllegalStateException("unexpectedly overlong thresholds");
    }

    // and go through the tables creating consistently
    // munged table names by shrinking the qualifier and item
    // names a consistent amount across all the fields it qualifies.
    for (Map.Entry<String, Name> tbl : tablePlaceholders.entrySet()) {
        Name nm = tbl.getValue();
        nm.mungedPrefix = trimName(nm.prefix, fixTblPrefixLen);
        nm.mungedQualifier = trimName(nm.qualifier, fixTblQualLen);
        nm.mungedItemName = trimName(nm.itemName, fixTblItemLen);
        if (nm.mungedPrefix.length() != 0) {
            nm.resolvedName = nm.mungedPrefix + "_";
        } else {
            nm.resolvedName = "";
        }
        if (nm.mungedQualifier.length() != 0) {
            nm.resolvedName += nm.mungedQualifier + "_";
        }
        nm.resolvedName += nm.mungedItemName;

        if (nm.resolvedName.length() > maxLenTableName) {
            logger.error("Munged resolved name still too long: " + nm.resolvedName);
            nm.resolvedName = trimName(nm.resolvedName, maxLenTableName);
        }
    }

    // we now have the set of candidate resolved names.
    // build a set of these to ensure no collisions either amongst
    // each other or with any existing tables in the datastore.
    // If we find a collision, resolve by appending suffix count
    // and re-trimming as needed.
    for (Map.Entry<String, Name> tbl : tablePlaceholders.entrySet()) {
        Name nm = tbl.getValue();
        if (uniqueTables.contains(nm.resolvedName) || ds.hasRelation(nm.schema, nm.resolvedName, user)) {
            // collision
            int dupCounter = 2;
            String newName = trimName(nm.resolvedName + Integer.toString(dupCounter++), maxLenTableName);
            while (uniqueTables.contains(newName) || ds.hasRelation(nm.schema, newName, user)) {
                newName = trimName(nm.resolvedName + Integer.toString(dupCounter++), maxLenTableName);
            }
            nm.resolvedName = newName;
        }
        uniqueTables.add(nm.resolvedName);
    }
    // OK. At this point, we have found good table names!
    // let's hope that the tables don't need to be split into phantoms...
}