Example usage for java.util LinkedHashMap keySet

List of usage examples for java.util LinkedHashMap keySet

Introduction

In this page you can find the example usage for java.util LinkedHashMap keySet.

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.redhat.rcm.version.Cli.java

private void testConfigAndPrintDiags() {
    VersionManagerSession session = null;
    final List<VManException> errors = new ArrayList<VManException>();
    try {/*  w ww  .j a v  a  2 s .c  om*/
        session = initSession();
    } catch (final VManException e) {
        errors.add(e);
    }

    if (session != null) {
        try {
            vman.configureSession(boms, toolchain, session);
        } catch (final VManException e) {
            errors.add(e);
        }
    }

    final FullProjectKey toolchainKey = session == null ? null : session.getToolchainKey();
    final List<FullProjectKey> bomCoords = session == null ? null : session.getBomCoords();

    final LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("Bootstrap location:", bootstrapLocation);
    map.put("Bootstrap read?", bootstrapRead);
    map.put("Config location:", configLocation);
    map.put("", "");
    map.put(" ", "");
    map.put("Toolchain location:", toolchain);
    map.put("Toolchain:", toolchainKey);
    map.put("    ", "");
    map.put("BOM locations:", boms);
    map.put("BOMs:", bomCoords);
    map.put("  ", "");
    map.put("   ", "");
    map.put("Settings.xml:", settings);
    map.put("Remote repo:", remoteRepositories);

    System.out.println("Version information:\n-------------------------------------------------\n\n");
    printVersionInfo();
    System.out.printf("Diagnostics:\n-------------------------------------------------\n\n");
    int max = 0;
    for (final String key : map.keySet()) {
        max = Math.max(max, key.length());
    }

    final StringBuilder indent = new StringBuilder();
    for (int i = 0; i < max + 4; i++) {
        indent.append(' ');
    }

    final int descMax = 75 - max;
    final String fmt = "%-" + max + "s    %-" + descMax + "s\n";
    for (final Map.Entry<String, Object> entry : map.entrySet()) {
        final Object value = entry.getValue();

        String val = value == null ? "-NONE-" : String.valueOf(value);
        if (value instanceof Collection<?>) {
            final Collection<?> coll = ((Collection<?>) value);
            if (coll.isEmpty()) {
                val = "-NONE-";
            } else {
                val = join(coll, "\n" + indent) + "\n";
            }
        }

        System.out.printf(fmt, entry.getKey(), val);
    }

    System.out.println();
    System.out.printf("Errors:\n-------------------------------------------------\n%s\n\n",
            errors.isEmpty() ? "-NONE" : join(errors, "\n\n"));
    System.out.println();
}

From source file:org.drools.semantics.builder.model.inference.DelegateInferenceStrategy.java

private void reduceTransitiveInheritance(LinkedHashMap<String, Concept> sortedCache,
        Map<String, Collection<String>> supers) {
    Map<String, Collection<String>> taboos = new HashMap<String, Collection<String>>();
    for (String con : sortedCache.keySet()) {
        Collection<String> ancestors = supers.get(con);
        Set<String> taboo = new HashSet<String>();
        for (String anc : ancestors) {
            if (taboos.containsKey(anc)) {
                taboo.addAll(taboos.get(anc));
            }//from w w  w .java2s  .c o m
        }
        ancestors.removeAll(taboo);
        taboo.addAll(ancestors);
        taboos.put(con, taboo);
    }
}

From source file:edu.umd.ks.cm.util.siscm.dao.impl.SisCmDaoImpl.java

private String getNaturalLanguageForStatement(String booleanExpression,
        List<ReqComponentReference> reqComponentList) throws Exception {
    HashMap reqComponentMap = new HashMap();
    LinkedHashMap<Integer, Integer> parPositionMap = new LinkedHashMap<Integer, Integer>();
    ArrayList<Integer> parLeftList = new ArrayList<Integer>();

    for (ReqComponentReference reqComponent : reqComponentList) {
        String translation = this.reqComponentTranslator.translate(reqComponent.getReqComponent(),
                "KUALI.RULE.CATALOG", "en");
        if (translation != null && translation.length() > 0
                && translation.substring(translation.length() - 1).equals("."))
            translation = translation.substring(0, translation.length() - 1);
        reqComponentMap.put(reqComponent.getBooleanId(), translation);
    }// www  .  j  a  v  a2  s  .co m

    BooleanFunction booleanFunction = new BooleanFunction(booleanExpression);
    List<String> funcSymbs = booleanFunction.getSymbols();

    for (int i = 0; i < funcSymbs.size(); i++) {
        if (funcSymbs.get(i).equals("(")) {
            parLeftList.add(i);
        }
        int parLeftLast = parLeftList.size() - 1;
        if (funcSymbs.get(i).equals(")")) {
            parPositionMap.put(parLeftList.get(parLeftLast), i);
            parLeftList.remove(parLeftLast);
        }
    }

    // For the expression (A + B + (C * D)) want to remove outer ()
    if (parPositionMap.containsKey(0) && parPositionMap.get(0) == funcSymbs.size() - 1) {
        parPositionMap.remove(0);
        funcSymbs.set(0, "null");
        funcSymbs.set(funcSymbs.size() - 1, "null");
    }

    if (!parPositionMap.isEmpty()) {
        for (Integer key : parPositionMap.keySet()) {
            StringBuffer funcSymb = new StringBuffer("");
            int pos = 0;
            String expr = "";
            for (int i = key + 1; i < parPositionMap.get(key); i++) {
                String funcSymbAdd = funcSymbs.get(i);
                if (!funcSymbAdd.equals("+") && !funcSymbAdd.equals("*") && !funcSymbAdd.equals("null")) {
                    expr = (String) reqComponentMap.get(funcSymbAdd);
                    if (pos == 0 && !funcSymbAdd.substring(0, 1).equals("V") && expr.length() > 2
                            && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")")) {
                        expr = expr.substring(1, expr.length() - 1);
                    }
                    pos = 1;

                    //convert the first character of 'expr' to lower case, if necessary
                    if (expr.length() > 0) {
                        char ch0 = expr.charAt(0);
                        if (ch0 <= 'Z' && ch0 >= 'A') {
                            if (expr.length() > 1) {
                                char ch1 = expr.charAt(1);
                                if (ch1 >= 'a' && ch1 <= 'z') {
                                    expr = expr.substring(0, 1).toLowerCase() + expr.substring(1);
                                }
                            } else {
                                expr = expr.toLowerCase();
                            }
                        }
                    }

                    funcSymb.append(expr);
                } else if (funcSymbAdd.equals("+")) {
                    funcSymb.append("; or ");
                } else if (funcSymbAdd.equals("*")) {
                    funcSymb.append("; and ");
                }
            } // for int i               
            String id = "V" + Integer.toString(key);
            funcSymb.insert(0, "(");
            funcSymb.append(")");
            reqComponentMap.put(id, funcSymb.toString());

            funcSymbs.set(key, id);
            for (int i = key + 1; i < parPositionMap.get(key) + 1; i++)
                funcSymbs.set(i, "null");
        }
    }

    List<String> funcSymbsNew = new ArrayList<String>();
    for (int i = 0; i < funcSymbs.size(); i++) {
        if (!funcSymbs.get(i).equals("null"))
            funcSymbsNew.add(funcSymbs.get(i));
    }

    String nl = "";
    if (funcSymbsNew.size() == 1) {
        nl = (String) reqComponentMap.get(funcSymbsNew.get(0));
        if (nl.substring(0, 1).equals("(") && nl.substring(nl.length() - 1).equals(")"))
            nl = nl.substring(1, nl.length() - 1);
    } else {
        int pos = 0;
        String expr = "";
        for (int i = 0; i < funcSymbsNew.size(); i++) {
            if (!funcSymbsNew.get(i).equals("*") && !funcSymbsNew.get(i).equals("+")) {
                expr = (String) reqComponentMap.get(funcSymbsNew.get(i));
                if (pos == 0) {
                    if (expr.length() > 2 && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")"))
                        expr = expr.substring(1, expr.length() - 1);
                    pos = 1;
                } else {
                    if (funcSymbsNew.get(i).substring(0, 1).equals("V") && expr.length() > 2
                            && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")"))
                        expr = expr.substring(1, expr.length() - 1);
                }
                nl = nl + expr;
            } else if (funcSymbsNew.get(i).equals("+")) {
                if ((i > 0 && funcSymbsNew.get(i - 1).substring(0, 1).equals("V"))
                        || (i < (funcSymbsNew.size() - 1)
                                && funcSymbsNew.get(i + 1).substring(0, 1).equals("V")))
                    nl = nl + ". Or ";
                else
                    nl = nl + "; or ";
            } else if (funcSymbsNew.get(i).equals("*")) {
                if ((i > 0 && funcSymbsNew.get(i - 1).substring(0, 1).equals("V"))
                        || (i < (funcSymbsNew.size() - 1)
                                && funcSymbsNew.get(i + 1).substring(0, 1).equals("V")))
                    nl = nl + ". And ";
                else
                    nl = nl + "; and ";
            }
        }
    }

    //TODO: Fix Capitalization
    nl = nl.substring(0, 1).toUpperCase() + nl.substring(1);
    return nl.trim();
}

From source file:org.openmrs.module.chica.DynamicFormAccess.java

/**
 * Populate all the form fields marked as "Merge Field".
 * /*from  w  w  w  .  j a  va2s  . co m*/
 * @param formId The form identifier.
 * @param formInstanceId The form instance identifier.
 * @param encounterId The encounter identifier associated with the form.
 * @return List of Field object containing field information as well the results of populating the fields.
 */
public List<Field> getMergeElements(Integer formId, Integer formInstanceId, Integer encounterId) {
    List<Field> fields = new ArrayList<Field>();
    EncounterService encounterService = Context.getEncounterService();
    Encounter encounter = encounterService.getEncounter(encounterId);
    Integer locationId = encounter.getLocation().getLocationId();

    LocationService locationService = Context.getLocationService();
    Location location = locationService.getLocation(locationId);

    FormService formService = Context.getFormService();
    Form form = formService.getForm(formId);

    FormInstance formInstance = new FormInstance(locationId, formId, formInstanceId);
    PatientState patientState = org.openmrs.module.atd.util.Util
            .getProducePatientStateByFormInstanceAction(formInstance);
    Integer locationTagId = patientState.getLocationTagId();

    HashMap<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("sessionId", patientState.getSessionId());
    parameters.put("formInstance", new FormInstance(locationId, formId, formInstanceId));
    parameters.put("locationTagId", locationTagId);
    parameters.put("locationId", locationId);
    parameters.put("location", location.getName());
    parameters.put("encounterId", encounterId);
    parameters.put("mode", "PRODUCE");

    Patient patient = patientState.getPatient();
    ATDService atdService = Context.getService(ATDService.class);
    FieldType mergeType = getFieldType("Merge Field");
    List<FieldType> fieldTypes = new ArrayList<FieldType>();
    fieldTypes.add(mergeType);
    LinkedHashMap<FormField, Object> fieldToResult = new LinkedHashMap<FormField, Object>();
    List<FormField> formFields = Context.getService(ChirdlUtilBackportsService.class).getFormFields(form,
            fieldTypes, false);
    for (FormField currFormField : formFields) {
        org.openmrs.Field currField = currFormField.getField();

        //fix lazy initialization error
        //currField = formService.getField(currField.getFieldId());

        String defaultValue = currField.getDefaultValue();
        if (defaultValue == null) {
            continue;
        }

        parameters.put("formFieldId", currFormField.getFormFieldId()); // DWE CHICA-437

        //store the leaf index as the result if the
        //current field has a parent
        if (currFormField.getParent() == null) {
            Result result = atdService.evaluateRule(defaultValue, patient, parameters);
            fieldToResult.put(currFormField, result);
        }
    }

    //process Results
    LinkedHashMap<String, String> fieldNameResult = new LinkedHashMap<String, String>();
    for (FormField currFormField : fieldToResult.keySet()) {
        String resultString = null;

        //fix lazy initialization error
        //org.openmrs.Field currField = formService.getField(currFormField.getField().getFieldId());
        org.openmrs.Field currField = currFormField.getField();
        String fieldName = currField.getName();
        Object fieldResult = fieldToResult.get(currFormField);

        if (fieldResult == null) {
            continue;
        }

        if (fieldResult instanceof Result) {
            resultString = ((Result) fieldResult).get(0).toString();
        } else {
            resultString = (String) fieldResult;
        }

        if (resultString != null) {
            //remove everything at or after the @ symbol (i.e. @Spanish)
            int atIndex = resultString.indexOf("@");
            if (atIndex >= 0) {
                resultString = resultString.substring(0, atIndex);
            }
        }

        fieldNameResult.put(fieldName, resultString);
    }

    for (String fieldName : fieldNameResult.keySet()) {
        String resultString = fieldNameResult.get(fieldName);
        if (resultString == null) {
            continue;
        }

        Field field = new Field();
        field.setId(fieldName);
        field.setValue(resultString);
        fields.add(field);
    }

    //Process rules with null priority that have @ value in write action
    //These rules directly write results to a specific field
    DssService dssService = Context.getService(DssService.class);
    List<RuleEntry> nonPriorRuleEntries = dssService.getNonPrioritizedRuleEntries(form.getName());

    for (RuleEntry currRuleEntry : nonPriorRuleEntries) {
        Rule currRule = currRuleEntry.getRule();
        if (currRule.checkAgeRestrictions(patient)) {
            currRule.setParameters(parameters);
            Result result = dssService.runRule(patient, currRule);
            for (Result currResult : result) {
                String resultString = currResult.toString();
                mapResult(resultString, fields);
            }
        }
    }

    serializeFields(formInstance, locationTagId, fields, new ArrayList<String>()); // DWE CHICA-430 Add new ArrayList<String>()
    return fields;
}

From source file:com.joey.software.Launcher.microneedleAnalysis.DataAnalysisViewer.java

public XYSeriesCollection getAllFingerData() {
    XYSeriesCollection collection = new XYSeriesCollection();

    LinkedHashMap<String, XYSeries> skinData = new LinkedHashMap<String, XYSeries>();
    LinkedHashMap<String, XYSeries> poreData = new LinkedHashMap<String, XYSeries>();
    LinkedHashMap<String, XYSeries> poreSkinData = new LinkedHashMap<String, XYSeries>();
    LinkedHashMap<String, XYSeries> totalData = new LinkedHashMap<String, XYSeries>();
    ArrayList<MeasurmentData> measureData = owner.measures;
    for (MeasurmentData measure : measureData) {
        if (validMeasurment(measure)) {
            String key = MicroNeedleAnalysis.clearLabel(measure.view, "abcdefghijklmnopqrstuvwxyz0123456789");

            XYSeries skin = skinData.get(key);
            XYSeries pore = poreData.get(key);
            XYSeries poreSkin = poreSkinData.get(key);
            XYSeries total = totalData.get(key);

            if (skin == null) {
                skin = new XYSeries(key + " Skin");
                skinData.put(key, skin);
            }/*from  w ww .j  av  a 2s  .  c  o  m*/

            if (pore == null) {
                pore = new XYSeries(key + " Pore");
                poreData.put(key, pore);
            }

            if (poreSkin == null) {
                poreSkin = new XYSeries(key + " Pore Skin");
                poreSkinData.put(key, poreSkin);
            }

            if (total == null) {
                total = new XYSeries(key + " Total");
                totalData.put(key, total);
            }

            int time;
            try {
                time = Integer.parseInt(MicroNeedleAnalysis.clearLabel(measure.exp, "0123456789"));
            } catch (Exception e) {
                time = -10;
            }

            skin.add(time, measure.skinDim.getValue());
            pore.add(time, measure.poreDim.getValue());
            poreSkin.add(time, measure.skinPoreDim.getValue());
            total.add(time, (measure.poreDim.getValue() + measure.skinPoreDim.getValue()));
        }
    }

    String[] keys = skinData.keySet().toArray(new String[0]);
    for (String key : keys) {
        XYSeries skin = skinData.get(key);
        XYSeries pore = poreData.get(key);
        XYSeries poreSkin = poreSkinData.get(key);
        XYSeries total = totalData.get(key);
        if (useSkin.isSelected()) {
            collection.addSeries(skin);
        }

        if (usePore.isSelected()) {
            collection.addSeries(pore);
        }

        if (usePoreSkin.isSelected()) {
            collection.addSeries(poreSkin);
        }

        if (useTotal.isSelected()) {
            collection.addSeries(total);
        }
    }
    return collection;
}

From source file:service.EventService.java

public void changeAllUsersCampaignAssignation(Long campaignId, Long userFromId, String[] clientNumArray,
        Long[] userIdArray, Long pkId) {
    if (pkId != null && getCampaign(campaignId) != null
            && getCampaign(campaignId).getCabinet().getPkId().equals(pkId)) {
        List<Event> evs;
        if (userFromId != null) {
            evs = eventDao.getAssignedNotClosedUserEvents(campaignId, userFromId, pkId);
        } else {//  w w  w .j  a v a  2  s  .c om
            evs = eventDao.getEventListNotProcessed(campaignId, pkId);
        }

        if (userIdArray != null && clientNumArray != null) {
            LinkedHashMap<Long, Integer> userIdCountAssignedMap = new LinkedHashMap();
            List<Event> eventsForUpdate = new ArrayList();
            PersonalCabinet pk = personalCabinetDao.find(pkId);
            int summClient = 0;
            if (userIdArray.length > 0 && evs.size() > 0 && clientNumArray.length > 0) {
                for (int i = 0; i < userIdArray.length; i++) {
                    if (clientNumArray.length >= i) {
                        int count = StringAdapter.toInteger(clientNumArray[i]);
                        summClient += count;
                        userIdCountAssignedMap.put(userIdArray[i], count);
                    } else {
                        userIdCountAssignedMap.put(userIdArray[i], 0);
                    }
                }
                int sindx = 0;
                if (summClient <= evs.size()) {
                    for (Long userId : userIdCountAssignedMap.keySet()) {
                        Integer eventsCountToAssign = userIdCountAssignedMap.get(userId);
                        User user = userDao.getUserBelongsPk(pk, userId);
                        if (user != null) {
                            for (int supCount = 0; supCount < eventsCountToAssign; supCount++) {
                                Event ev = evs.get(sindx);
                                if (ev != null && supCount < eventsCountToAssign) {
                                    ev.setUser(user);
                                    ev.setStatus(Event.ASSIGNED);
                                    if (validate(ev)) {
                                        eventsForUpdate.add(ev);
                                        sindx++;
                                    }
                                }
                            }
                        } else {
                            addError("!  id:" + userId
                                    + "     !");
                        }
                    }
                    for (Event ev : eventsForUpdate) {
                        eventDao.update(ev);
                        User u = ev.getUser();
                        addEventComment("   " + u.getShortName() + "("
                                + u.getEmail() + ")", EventComment.ASSIGN, ev, pkId);
                    }
                } else {
                    addError("?  " + summClient
                            + "  ?  : " + evs.size());
                }
            }
        }
    } else {
        addError(
                "  ! ?  ? !");
    }
}

From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

/**
 * Process the serversLogPresenceList and gets the actual log files/folder for each base log folder. This is done by
 * iterating the {@link LogsDownloaderWorker#getServersList()} depending on its presence.
 * /*from  w  ww  .ja v  a  2s  .com*/
 * @param serversLogPresenceList Map for each base log folder and servers presence as values (space separated list
 *            of servers keys)
 * @return
 */
private LinkedList<LogFolderInfo> getFromServersCompleteLogList(
        LinkedHashMap<String, String> serversLogPresenceList) {
    if (serversLogPresenceList.size() == 0)
        return new LinkedList<LogFolderInfo>();

    long timeF0 = System.currentTimeMillis();

    LinkedList<LogFolderInfo> tmpLogFolders = new LinkedList<LogFolderInfo>();

    try {
        ArrayList<String> servers = worker.getServersList();
        for (String serverKey : servers) { // Let's iterate by servers first
            if (stopLogListProcessing)
                break;

            if (!worker.isServerAvailable(serverKey))
                continue;

            FtpDownloader ftpServer = null;
            try {
                ftpServer = LogsDownloaderWorkerUtil.getOrRenewFtpDownloader(serverKey,
                        worker.getFtpDownloaders(), worker.getHostFor(serverKey), worker.getPortFor(serverKey));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (ftpServer == null)
                continue;

            // String host = worker.getHostFor(serverKey); // To fill the log files host info
            String host = serverKey; // Using a key instead of host directly

            for (String logDir : serversLogPresenceList.keySet()) { // For the server go through the folders
                if (stopLogListProcessing)
                    break;

                if (!serversLogPresenceList.get(logDir).contains(serverKey))
                    continue;

                // This is needed to avoid problems with non English languages
                String isoStr = new String(logDir.getBytes(), "ISO-8859-1");

                LogFolderInfo lFolder = null;
                for (LogFolderInfo lfi : tmpLogFolders) {
                    if (lfi.getName().equals(logDir)) {
                        lFolder = lfi;
                        break;
                    }
                }
                if (lFolder == null)
                    lFolder = new LogFolderInfo(logDir);

                if (!ftpServer.isConnected())
                    ftpServer.renewClient();

                try {
                    FTPFile[] files = ftpServer.getClient().listFiles("/" + isoStr + "/");
                    for (FTPFile file : files) {
                        if (stopLogListProcessing)
                            break;

                        String name = logDir + "/" + file.getName();
                        String uriPartial = logDir + "/" + file.getName();
                        LogFileInfo logFileTmp = new LogFileInfo(name);
                        logFileTmp.setUriPartial(uriPartial);
                        logFileTmp.setSize(file.getSize());
                        logFileTmp.setFile(file);
                        logFileTmp.setHost(host);

                        // Let us see if its a directory
                        if (file.isDirectory()) {
                            logFileTmp.setSize(-1); // Set size to -1 if directory
                            long allSize = 0;

                            // Here there are no directories, considering only 2 folder layers only, e.g. "Photos/00000"
                            LinkedHashMap<String, FTPFile> dirListing = ftpServer
                                    .listDirectory(logFileTmp.getName());
                            ArrayList<LogFileInfo> directoryContents = new ArrayList<>();
                            for (String fName : dirListing.keySet()) {
                                if (stopLogListProcessing)
                                    break;

                                FTPFile fFile = dirListing.get(fName);
                                String fURIPartial = fName;
                                LogFileInfo fLogFileTmp = new LogFileInfo(fName);
                                fLogFileTmp.setUriPartial(fURIPartial);
                                fLogFileTmp.setSize(fFile.getSize());
                                fLogFileTmp.setFile(fFile);
                                fLogFileTmp.setHost(host);

                                allSize += fLogFileTmp.getSize();
                                directoryContents.add(fLogFileTmp);
                            }
                            logFileTmp.setDirectoryContents(directoryContents);
                            logFileTmp.setSize(allSize);
                        }
                        lFolder.addFile(logFileTmp);
                        tmpLogFolders.add(lFolder);
                    }
                } catch (Exception e) {
                    System.err.println(isoStr);
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    NeptusLog.pub().warn(".......Contacting remote systems for complete log file list "
            + (System.currentTimeMillis() - timeF0) + "ms");

    return tmpLogFolders;
}

From source file:org.broad.igv.track.PackedFeatures.java

/**
 * Allocates each feature to the rows such that there is no overlap.
 *
 * @param iter TabixLineReader wrapping the collection of alignments. Note that this should
 *             really be an Iterator<T>, but it can't be subclassed if that's the case.
 *///from   w  w w.  j a  va2s  . co  m
List<FeatureRow> packFeatures(Iterator iter) {

    List<FeatureRow> rows = new ArrayList(10);
    if (iter == null || !iter.hasNext()) {
        return rows;
    }

    maxFeatureLength = 0;
    int totalCount = 0;

    LinkedHashMap<Integer, PriorityQueue<T>> bucketArray = new LinkedHashMap();
    Comparator pqComparator = new Comparator<T>() {
        public int compare(Feature row1, Feature row2) {
            return (row2.getEnd() - row2.getStart()) - (row1.getEnd() - row2.getStart());
        }
    };

    // Allocate features to buckets,  1 bucket per base position
    while (iter.hasNext()) {
        T feature = (T) iter.next();
        maxFeatureLength = Math.max(maxFeatureLength,
                getFeatureEndForPacking(feature) - getFeatureStartForPacking(feature));
        features.add(feature);

        int bucketNumber = getFeatureStartForPacking(feature);

        PriorityQueue<T> bucket = bucketArray.get(bucketNumber);
        if (bucket == null) {
            bucket = new PriorityQueue<T>(5, pqComparator);
            bucketArray.put(bucketNumber, bucket);
        }
        bucket.add(feature);
        totalCount++;

    }

    // Allocate features to rows, pulling at most 1 per bucket for each row
    FeatureRow currentRow = new FeatureRow();
    int allocatedCount = 0;
    int nextStart = Integer.MIN_VALUE;

    int lastKey = 0;
    int lastAllocatedCount = -1;
    while (allocatedCount < totalCount && rows.size() < maxLevels) {

        // Check to prevent infinite loops
        if (lastAllocatedCount == allocatedCount) {

            if (IGV.hasInstance()) {
                String msg = "Infinite loop detected while packing features for track: " + getTrackName()
                        + ".<br>Not all features will be shown."
                        + "<br>Please contact igv-team@broadinstitute.org";

                log.error(msg);
                MessageUtils.showMessage(msg);
            }
            break;
        }
        lastAllocatedCount = allocatedCount;

        // Next row Loop through alignments until we reach the end of the interval

        PriorityQueue<T> bucket = null;
        // Advance to nextLine occupied bucket

        ArrayList<Integer> emptyBucketKeys = new ArrayList();
        for (Integer key : bucketArray.keySet()) {
            //if (key < lastKey) {
            //    String msg = "Features from track: " + trackName + " are not sorted.  Some features might not be shown.<br>" +
            //            "Please notify igv-help@broadinstitute.org";
            //    MessageUtils.showMessage(msg);
            //}
            lastKey = key;
            if (key >= nextStart) {
                bucket = bucketArray.get(key);

                T feature = bucket.poll();

                if (bucket.isEmpty()) {
                    emptyBucketKeys.add(key);
                }
                currentRow.addFeature(feature);
                nextStart = currentRow.end + FeatureTrack.MINIMUM_FEATURE_SPACING;
                allocatedCount++;
            }
        }
        for (Integer key : emptyBucketKeys) {
            bucketArray.remove(key);
        }

        // We've reached the end of the interval,  start a new row
        if (currentRow.features.size() > 0) {
            rows.add(currentRow);
            lastAllocatedCount = 0;
        }
        currentRow = new FeatureRow();
        nextStart = 0;
        lastKey = 0;

    }
    // Add the last row
    if (currentRow.features.size() > 0) {
        rows.add(currentRow);
    }

    return rows;
}

From source file:org.openmeetings.cli.OmHelpFormatter.java

@SuppressWarnings("unchecked")
private LinkedHashMap<String, List<OmOption>> getOptions(Options opts, int leftPad) {
    final String longOptSeparator = " ";
    final String lpad = createPadding(leftPad);
    final String lpadParam = createPadding(leftPad + 2);
    List<OmOption> reqOptions = getReqOptions(opts);
    LinkedHashMap<String, List<OmOption>> map = new LinkedHashMap<String, List<OmOption>>(reqOptions.size());
    map.put(GENERAL_OPTION_GROUP, new ArrayList<OmOption>());
    for (OmOption o : reqOptions) {
        map.put(o.getOpt(), new ArrayList<OmOption>());
    }/*from w  ww  .  jav  a  2 s. co  m*/
    for (OmOption o : (Collection<OmOption>) opts.getOptions()) {
        //TODO need better check (required option should go first and should not be duplicated
        boolean skipOption = map.containsKey(o.getOpt());
        boolean mainOption = skipOption || o.getGroup() == null;

        // first create list containing only <lpad>-a,--aaa where
        // -a is opt and --aaa is long opt; in parallel look for
        // the longest opt string this list will be then used to
        // sort options ascending
        StringBuilder optBuf = new StringBuilder();
        if (o.getOpt() == null) {
            optBuf.append(mainOption ? lpad : lpadParam).append("   ").append(getLongOptPrefix())
                    .append(o.getLongOpt());
        } else {
            optBuf.append(mainOption ? lpad : lpadParam).append(getOptPrefix()).append(o.getOpt());

            if (o.hasLongOpt()) {
                optBuf.append(',').append(getLongOptPrefix()).append(o.getLongOpt());
            }
        }

        if (o.hasArg()) {
            String argName = o.getArgName();
            if (argName != null && argName.length() == 0) {
                // if the option has a blank argname
                optBuf.append(' ');
            } else {
                optBuf.append(o.hasLongOpt() ? longOptSeparator : " ");
                optBuf.append("<").append(argName != null ? o.getArgName() : getArgName()).append(">");
            }
        }

        o.setHelpPrefix(optBuf);
        maxPrefixLength = Math.max(optBuf.length(), maxPrefixLength);

        if (skipOption) {
            //TODO need better check (required option should go first and should not be duplicated
            continue;
        }
        String grp = o.getGroup();
        grp = grp == null ? GENERAL_OPTION_GROUP : grp;
        String[] grps = grp.split(",");
        for (String g : grps) {
            map.get(g).add(o);
        }
    }
    for (String _key : map.keySet()) {
        final String key = _key;
        List<OmOption> options = map.get(key);
        Collections.sort(options, new Comparator<OmOption>() {
            public int compare(OmOption o1, OmOption o2) {
                boolean o1opt = !o1.isOptional(key);
                boolean o2opt = !o2.isOptional(key);
                return (o1opt && o2opt || !o1opt && !o2opt) ? (o1.getOpt() == null ? 1 : -1) : (o1opt ? -1 : 1);
            }

        });
        if (opts.hasOption(key)) {
            options.add(0, (OmOption) opts.getOption(key));
        }
    }
    return map;
}

From source file:com.vmware.bdd.manager.ClusterConfigManager.java

private LinkedHashMap<NetTrafficType, List<ClusterNetConfigInfo>> validateAndConvertNetNamesToNetConfigs(
        Map<NetTrafficType, List<String>> netNamesInfo, boolean isMaprDistro) {
    LinkedHashMap<NetTrafficType, List<ClusterNetConfigInfo>> netConfigs = new LinkedHashMap<NetTrafficType, List<ClusterNetConfigInfo>>();
    LinkedHashMap<String, Set<String>> port2names = new LinkedHashMap<String, Set<String>>();

    for (NetTrafficType type : netNamesInfo.keySet()) {
        netConfigs.put(type, new ArrayList<ClusterNetConfigInfo>());
        for (String name : netNamesInfo.get(type)) {
            NetworkEntity networkEntity = networkMgr.getNetworkEntityByName(name);

            String pg = networkEntity.getPortGroup();
            Boolean isGenerateHostname = networkEntity.getIsGenerateHostname();
            String hostnamePrefix = HostnameManager.getHostnamePrefix();

            ClusterNetConfigInfo netConfig = new ClusterNetConfigInfo(type, name, pg,
                    networkEntity.getDnsType(), isGenerateHostname, hostnamePrefix);
            netConfigs.get(type).add(netConfig);

            if (!port2names.containsKey(pg)) {
                port2names.put(pg, new HashSet<String>());
            }/*from  w  w  w .ja va2  s.  c om*/
            port2names.get(pg).add(name);
        }
    }

    if (isMaprDistro && port2names.size() > 1) {
        throw BddException.MULTI_NETWORKS_FOR_MAPR_DISTRO();
    }

    // if nw1,nw2 are both refer to pg1, should not use them in one cluster
    for (String pg : port2names.keySet()) {
        if (port2names.get(pg).size() > 1) {
            throw BddException.PG_REFERENCED_MULTI_TIMES();
        }
    }

    return netConfigs;
}