Example usage for java.util TreeMap firstKey

List of usage examples for java.util TreeMap firstKey

Introduction

In this page you can find the example usage for java.util TreeMap firstKey.

Prototype

public K firstKey() 

Source Link

Usage

From source file:org.apache.ambari.server.controller.metrics.timeline.cache.TimelineMetricCacheEntryFactory.java

/**
 * Update cache with new timeseries data
 *//*from www.j  a va  2 s .c om*/
protected void updateTimelineMetricsInCache(TimelineMetrics newMetrics,
        TimelineMetricsCacheValue timelineMetricsCacheValue, Long requestedStartTime, Long requestedEndTime,
        boolean removeAll) {

    TimelineMetrics existingTimelineMetrics = timelineMetricsCacheValue.getTimelineMetrics();

    // Remove values that do not fit before adding new data
    updateExistingMetricValues(existingTimelineMetrics, requestedStartTime, requestedEndTime, removeAll);

    if (newMetrics != null && !newMetrics.getMetrics().isEmpty()) {
        for (TimelineMetric timelineMetric : newMetrics.getMetrics()) {
            if (LOG.isTraceEnabled()) {
                TreeMap<Long, Double> sortedMetrics = new TreeMap<Long, Double>(
                        timelineMetric.getMetricValues());

                LOG.trace("New metric: " + timelineMetric.getMetricName() + " # "
                        + timelineMetric.getMetricValues().size() + ", startTime = " + sortedMetrics.firstKey()
                        + ", endTime = " + sortedMetrics.lastKey());
            }

            TimelineMetric existingMetric = null;

            for (TimelineMetric metric : existingTimelineMetrics.getMetrics()) {
                if (metric.equalsExceptTime(timelineMetric)) {
                    existingMetric = metric;
                }
            }

            if (existingMetric != null) {
                // Add new ones
                existingMetric.getMetricValues().putAll(timelineMetric.getMetricValues());

                if (LOG.isTraceEnabled()) {
                    TreeMap<Long, Double> sortedMetrics = new TreeMap<Long, Double>(
                            existingMetric.getMetricValues());
                    LOG.trace("Merged metric: " + timelineMetric.getMetricName() + ", " + "Final size: "
                            + existingMetric.getMetricValues().size() + ", startTime = "
                            + sortedMetrics.firstKey() + ", endTime = " + sortedMetrics.lastKey());
                }
            } else {
                existingTimelineMetrics.getMetrics().add(timelineMetric);
            }
        }
    }
}

From source file:com.wso2.code.quality.matrices.ChangesFinder.java

/**
 * Reading the blame received for a current selected file name and insert the parent commits of the changed lines,
 * relevant authors and the relevant commits hashes to look for the reviewers of those line ranges
 *
 * @param rootJsonObject                                JSONObject containing blame information for current selected file
 * @param arrayListOfRelevantChangedLinesOfSelectedFile arraylist containing the changed line ranges of the current selected file
 * @param gettingPr                                     should be true if running this method for finding the authors of buggy lines which are being fixed from  the patch
 */// w ww .j a  va  2 s . co m
public void readBlameReceivedForAFile(JSONObject rootJsonObject,
        ArrayList<String> arrayListOfRelevantChangedLinesOfSelectedFile, boolean gettingPr, String oldRange) {

    //running a iterator for fileName arrayList to get the location of the above saved file
    JSONObject dataJSONObject = (JSONObject) rootJsonObject.get(GITHUB_GRAPHQL_API_DATA_KEY_STRING);
    JSONObject repositoryJSONObect = (JSONObject) dataJSONObject.get(GITHUB_GRAPHQL_API_REPOSITORY_KEY_STRING);
    JSONObject objectJSONObject = (JSONObject) repositoryJSONObect.get(GITHUB_GRAPHQL_API_OBJECT_KEY_STRING);
    JSONObject blameJSONObject = (JSONObject) objectJSONObject.get(GITHUB_GRAPHQL_API_BLAME_KEY_STRING);
    JSONArray rangeJSONArray = (JSONArray) blameJSONObject.get(GITHUB_GRAPHQL_API_RANGES_KEY_STRING);

    //getting the starting line no of the range of lines that are modified from the patch
    // parallel streams are not used in here as the order of the arraylist is important in the process
    arrayListOfRelevantChangedLinesOfSelectedFile.stream().forEach(lineRanges -> {
        int startingLineNo = 0;
        int endLineNo = 0;
        String oldFileRange = StringUtils.substringBefore(lineRanges, "/");
        String newFileRange = StringUtils.substringAfter(lineRanges, "/");
        // need to skip the newly created files from taking the blame as they contain no previous commits
        if (!oldFileRange.equals("0,0")) {
            if (gettingPr && oldRange.equals(oldFileRange)) {
                // need to consider the line range in the old file for finding authors and reviewers
                startingLineNo = Integer.parseInt(StringUtils.substringBefore(oldFileRange, ","));
                endLineNo = Integer.parseInt(StringUtils.substringAfter(oldFileRange, ","));
            } else if (!gettingPr && oldRange == null) {
                // need to consider the line range in the new file resulted from applying the commit, for finding parent commits
                startingLineNo = Integer.parseInt(StringUtils.substringBefore(newFileRange, ","));
                endLineNo = Integer.parseInt(StringUtils.substringAfter(newFileRange, ","));
            } else {
                return; // to skip the to the next iteration if oldRange != oldFileRange when finding authornames and commits for obtaining PRs
            }

            // as a new mapForStoringAgeAndIndex map should be available for each line range to find the most recent change
            Map<Integer, ArrayList<Integer>> mapForStoringAgeAndIndex = new HashMap<Integer, ArrayList<Integer>>();

            //checking line by line by iterating the startingLineNo
            while (endLineNo >= startingLineNo) {
                // since the index value is required for later processing, without Java 8 features "for loop" is used for iteration
                for (int i = 0; i < rangeJSONArray.length(); i++) {
                    JSONObject rangeJSONObject = (JSONObject) rangeJSONArray.get(i);
                    int tempStartingLineNo = (int) rangeJSONObject
                            .get(GITHUB_GRAPHQL_API_STARTING_LINE_KEY_STRING);
                    int tempEndingLineNo = (int) rangeJSONObject.get(GITHUB_GRAPHQL_API_ENDING_LINE_KEY_STRING);

                    //checking whether the line belongs to that line range group
                    if ((tempStartingLineNo <= startingLineNo) && (tempEndingLineNo >= startingLineNo)) {
                        // so the relevant startingLineNo belongs in this line range in other words in this JSONObject
                        if (!gettingPr) {
                            int age = (int) rangeJSONObject.get(GITHUB_GRAPHQL_API_AGE_KEY_STRING);
                            // storing the age field with relevant index of the JSONObject
                            mapForStoringAgeAndIndex.putIfAbsent(age, new ArrayList<Integer>());
                            if (!mapForStoringAgeAndIndex.get(age).contains(i)) {
                                mapForStoringAgeAndIndex.get(age).add(i); // adding if the index is not present in the array list for the relevant age
                            }

                        } else {
                            //for saving the author names of commiters
                            JSONObject commitJSONObject = (JSONObject) rangeJSONObject
                                    .get(GITHUB_GRAPHQL_API_COMMIT_KEY_STRING);

                            JSONObject authorJSONObject = (JSONObject) commitJSONObject
                                    .get(GITHUB_GRAPHQL_API_AUTHOR_KEY_STRING);
                            String nameOfTheAuthor = (String) authorJSONObject
                                    .get(GITHUB_GRAPHQL_API_NAME_KEY_STRING);
                            authorNames.add(nameOfTheAuthor); // authors are added to the Set

                            String urlOfCommit = (String) commitJSONObject
                                    .get(GITHUB_GRAPHQL_API_URL_KEY_STRING);
                            String commitHashForPRReview = StringUtils.substringAfter(urlOfCommit, "commit/");
                            commitHashObtainedForPRReview.add(commitHashForPRReview);
                        }
                        break;
                    } else {
                        continue; // to skip to the next JSON Object in the rangeJSONArray
                    }
                }
                startingLineNo++; // to check for other line numbers
            }

            //for the above line range getting the lastest commit which modified the lines
            if (!gettingPr) {
                //converting the map into a treeMap to get it ordered
                TreeMap<Integer, ArrayList<Integer>> treeMap = new TreeMap<>(mapForStoringAgeAndIndex);
                int minimumKeyOfMapForStoringAgeAndIndex = treeMap.firstKey(); // getting the minimum key
                //getting the relevant JSONObject indexes which consists of the recent change with in the relevant line range
                ArrayList<Integer> indexesOfJsonObjectForRecentCommit = mapForStoringAgeAndIndex
                        .get(minimumKeyOfMapForStoringAgeAndIndex);
                // the order of the indexesOfJsonObjectForRecentCommit is not important as we only need to get the parent commit hashes
                indexesOfJsonObjectForRecentCommit.parallelStream().forEach(index -> {
                    JSONObject rangeJSONObject = (JSONObject) rangeJSONArray.get(index);
                    JSONObject commitJSONObject = (JSONObject) rangeJSONObject
                            .get(GITHUB_GRAPHQL_API_COMMIT_KEY_STRING);
                    JSONObject historyJSONObject = (JSONObject) commitJSONObject
                            .get(GITHUB_GRAPHQL_API_HISTORY_KEY_STRING);
                    JSONArray edgesJSONArray = (JSONArray) historyJSONObject
                            .get(GITHUB_GRAPHQL_API_EDGE_KEY_STRING);
                    //getting the second json object from the array as it contain the commit of the parent which modified the above line range
                    JSONObject edgeJSONObject = (JSONObject) edgesJSONArray.get(1);
                    JSONObject nodeJSONObject = (JSONObject) edgeJSONObject
                            .get(GITHUB_GRAPHQL_API_NODE_KEY_STRING);
                    String urlOfTheParentCommit = (String) nodeJSONObject
                            .get(GITHUB_GRAPHQL_API_URL_KEY_STRING); // this contain the URL of the parent commit
                    String commitHash = (String) StringUtils.substringAfter(urlOfTheParentCommit, "commit/");
                    //                                        commitHashesOfTheParent.add(commitHash);    // commitHashesof the parent for the selected file

                    commitHashesMapOfTheParent.putIfAbsent(oldFileRange, new HashSet<String>());
                    if (!commitHashesMapOfTheParent.get(oldFileRange).contains(commitHash)) {
                        commitHashesMapOfTheParent.get(oldFileRange).add(commitHash);
                    }
                });
            }

        }

    });
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Identify the latest core, populates the htaccess redirect file, optionally download the core wars and build the index.html
 * @return the JSON for the core Jenkins
 *///from   ww w.  j a v  a  2  s  . co m
protected JSONObject buildCore(MavenRepository repository, PrintWriter redirect) throws Exception {
    TreeMap<VersionNumber, HudsonWar> wars = repository.getHudsonWar();
    if (wars.isEmpty())
        return null;

    HudsonWar latest = wars.get(wars.firstKey());
    JSONObject core = latest.toJSON("core");
    System.out.println("core\n=> " + core);

    redirect.printf("Redirect 302 /latest/jenkins.war %s\n", latest.getURL().getPath());
    redirect.printf(
            "Redirect 302 /latest/debian/jenkins.deb http://pkg.jenkins-ci.org/debian/binary/jenkins_%s_all.deb\n",
            latest.getVersion());
    redirect.printf(
            "Redirect 302 /latest/redhat/jenkins.rpm http://pkg.jenkins-ci.org/redhat/RPMS/noarch/jenkins-%s-1.1.noarch.rpm\n",
            latest.getVersion());
    redirect.printf(
            "Redirect 302 /latest/opensuse/jenkins.rpm http://pkg.jenkins-ci.org/opensuse/RPMS/noarch/jenkins-%s-1.1.noarch.rpm\n",
            latest.getVersion());

    if (latestCoreTxt != null)
        writeToFile(latest.getVersion().toString(), latestCoreTxt);

    if (download != null) {
        // build the download server layout
        for (HudsonWar w : wars.values()) {
            stage(w, new File(download, "war/" + w.version + "/" + w.getFileName()));
        }
    }

    if (www != null)
        buildIndex(new File(www, "download/war/"), "jenkins.war", wars.values(), "/latest/jenkins.war");

    return core;
}

From source file:com.datatorrent.contrib.hdht.PurgeTest.java

/**
 * Purge data from start of the file./* ww  w.  jav  a  2 s.  c o  m*/
 */
@Test
public void testMultiplePurgeFromDataFiles() throws IOException {
    File file = new File(testInfo.getDir());
    FileUtils.deleteDirectory(file);

    FileAccessFSImpl fa = new MockFileAccess();
    fa.setBasePath(file.getAbsolutePath());
    HDHTWriter hds = new HDHTWriter();
    hds.setFileStore(fa);
    hds.setFlushSize(0); // flush after every key
    hds.setFlushIntervalCount(0);
    hds.setup(new OperatorContextTestHelper.TestIdOperatorContext(0, new DefaultAttributeMap()));

    hds.writeExecutor = MoreExecutors.sameThreadExecutor(); // synchronous flush
    hds.beginWindow(1);
    for (int i = 100; i < 1000; i++) {
        hds.put(1, newSlice(i), newData(i));
    }
    hds.endWindow();
    hds.checkpointed(1);
    hds.committed(1);

    HDHTReader.BucketMeta meta = hds.loadBucketMeta(1);
    HDHTReader.BucketFileMeta fmeta = meta.files.firstEntry().getValue();

    hds.beginWindow(2);
    hds.purge(1, newSlice(0), newSlice(150));
    hds.endWindow();
    hds.checkpointed(2);
    hds.committed(2);

    meta = hds.loadBucketMeta(1);
    fmeta = meta.files.firstEntry().getValue();
    TreeMap<Slice, Slice> data = getData(fa, 1, fmeta.name);
    int startKey = sliceToInt(data.firstKey());
    Assert.assertEquals("The start key in new file", 151, startKey);
    int endKey = sliceToInt(data.lastKey());
    Assert.assertEquals("The end key in neww file", 999, endKey);
}

From source file:com.datatorrent.contrib.hdht.PurgeTest.java

/**
 * Purge data from start, middle and end of the file.
 *///w  w w.ja  v a2  s .c om
@Test
public void purgeDataFromMiddleOfFile() throws IOException {
    File file = new File(testInfo.getDir());
    FileUtils.deleteDirectory(file);

    FileAccessFSImpl fa = new MockFileAccess();
    fa.setBasePath(file.getAbsolutePath());
    HDHTWriter hds = new HDHTWriter();
    hds.setFileStore(fa);
    hds.setFlushSize(0); // flush after every key
    hds.setFlushIntervalCount(0);
    hds.setup(new OperatorContextTestHelper.TestIdOperatorContext(0, new DefaultAttributeMap()));
    hds.writeExecutor = MoreExecutors.sameThreadExecutor(); // synchronous flush

    hds.beginWindow(1);
    for (int i = 100; i < 1000; i++) {
        hds.put(1, newSlice(i), newData(i));
    }
    hds.endWindow();
    hds.checkpointed(1);
    hds.committed(1);

    hds.beginWindow(2);
    hds.purge(1, newSlice(150), newSlice(250));
    hds.purge(1, newSlice(200), newSlice(400));
    hds.purge(1, newSlice(450), newSlice(700));
    hds.purge(1, newSlice(950), newSlice(1500));
    hds.endWindow();
    hds.checkpointed(2);
    hds.committed(2);

    HDHTReader.BucketFileMeta fmeta = hds.loadBucketMeta(1).files.firstEntry().getValue();
    TreeMap<Slice, Slice> data = getData(fa, 1, fmeta.name);
    int startKey = sliceToInt(data.firstKey());
    Assert.assertEquals("The start key in new file", 100, startKey);
    int endKey = sliceToInt(data.lastKey());

    Assert.assertArrayEquals("Key 149 is present in file ", newData(149),
            data.get(newSlice(149)).toByteArray());
    Assert.assertEquals("Key 150 is removed from file ", null, data.get(newSlice(150)));
    Assert.assertEquals("Key 160 is removed from file ", null, data.get(newSlice(160)));
    Assert.assertEquals("Key 220 is removed from file ", null, data.get(newSlice(220)));
    Assert.assertEquals("Key 400 is removed from file ", null, data.get(newSlice(400)));
    Assert.assertArrayEquals("Key 401 is present in file ", newData(401),
            data.get(newSlice(401)).toByteArray());

    Assert.assertArrayEquals("Key 449 is present in file ", newData(449),
            data.get(newSlice(449)).toByteArray());
    Assert.assertEquals("Key 450 is removed from file ", null, data.get(newSlice(450)));
    Assert.assertEquals("Key 500 is removed from file ", null, data.get(newSlice(500)));
    Assert.assertEquals("Key 700 is removed from file ", null, data.get(newSlice(700)));
    Assert.assertArrayEquals("Key 701 is present in file ", newData(701),
            data.get(newSlice(701)).toByteArray());

    Assert.assertArrayEquals("Key 949 is present in file ", newData(949),
            data.get(newSlice(949)).toByteArray());
    Assert.assertEquals("Key 950 is removed from file ", null, data.get(newSlice(950)));
    Assert.assertEquals("Key 999 is removed from file ", null, data.get(newSlice(999)));

    Assert.assertEquals("The end key in new file", 949, endKey);
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Identify the latest core, populates the htaccess redirect file, optionally download the core wars and build the
 * index.html/*from ww  w .  j a  v a 2  s  .c  o  m*/
 *
 * @return the JSON for the core Jenkins
 */
protected JSONObject buildCore(MavenRepository repository, PrintWriter redirect) throws Exception {
    TreeMap<VersionNumber, HudsonWar> wars = repository.getHudsonWar();
    if (wars.isEmpty()) {
        return null;
    }

    HudsonWar latest = wars.get(wars.firstKey());
    latest.file = repository.resolve(latest.artifact);
    JSONObject core = latest.toJSON("core");
    System.out.println("core\n=> " + core);

    redirect.printf("Redirect 302 /latest/jenkins.war %s\n", latest.getURL().getPath());
    redirect.printf(
            "Redirect 302 /latest/debian/jenkins.deb http://pkg.jenkins-ci.org/debian/binary/jenkins_%s_all.deb\n",
            latest.getVersion());
    redirect.printf(
            "Redirect 302 /latest/redhat/jenkins.rpm http://pkg.jenkins-ci.org/redhat/RPMS/noarch/jenkins-%s-1.1.noarch.rpm\n",
            latest.getVersion());
    redirect.printf(
            "Redirect 302 /latest/opensuse/jenkins.rpm http://pkg.jenkins-ci.org/opensuse/RPMS/noarch/jenkins-%s-1.1.noarch.rpm\n",
            latest.getVersion());

    if (latestCoreTxt != null) {
        writeToFile(latest.getVersion().toString(), latestCoreTxt);
    }

    if (download != null) {
        // build the download server layout
        for (HudsonWar w : wars.values()) {
            stage(w, new File(download, "war/" + w.version + "/" + w.getFileName()));
        }
    }

    if (www != null) {
        buildIndex(new File(www, "download/war/"), "jenkins.war", wars.values(), "/latest/jenkins.war");
    }

    return core;
}

From source file:org.kuali.ole.module.purap.document.web.struts.ReceivingBaseAction.java

/**
 * Builds and asks questions which require text input by the user for a payment request or a credit memo.
 *
 * @param mapping               An ActionMapping
 * @param form                  An ActionForm
 * @param request               The HttpServletRequest
 * @param response              The HttpServletResponse
 * @param questionType          A String used to distinguish which question is being asked
 * @param notePrefix            A String explaining what action was taken, to be prepended to the note containing the reason, which gets
 *                              written to the document
 * @param operation             A one-word String description of the action to be taken, to be substituted into the message. (Can be an
 *                              empty String for some messages.)
 * @param messageKey            A (whole) key to the message which will appear on the question screen
 * @param questionsAndCallbacks A TreeMap associating the type of question to be asked and the type of callback which should
 *                              happen in that case
 * @param messagePrefix         The most general part of a key to a message text to be retrieved from ConfigurationService,
 *                              Describes a collection of questions.
 * @param redirect              An ActionForward to return to if done with questions
 * @return An ActionForward/*  w w  w.  j  a  va2  s .  c om*/
 * @throws Exception
 */
protected ActionForward askQuestionWithInput(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String questionType, String notePrefix, String operation,
        String messageKey, TreeMap<String, ReceivingQuestionCallback> questionsAndCallbacks,
        String messagePrefix, ActionForward redirect) throws Exception {
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
    ReceivingDocument receivingDocument = (ReceivingDocument) kualiDocumentFormBase.getDocument();

    String question = (String) request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
    String reason = request.getParameter(OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME);
    String noteText = "";

    ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
    String firstQuestion = questionsAndCallbacks.firstKey();
    ReceivingQuestionCallback callback = null;
    Iterator questions = questionsAndCallbacks.keySet().iterator();
    String mapQuestion = null;
    String key = null;

    // Start in logic for confirming the close.
    if (question == null) {
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, firstQuestion);
        String message = StringUtils.replace(key, "{0}", operation);

        // Ask question if not already asked.
        return this.performQuestionWithInput(mapping, form, request, response, firstQuestion, message,
                OLEConstants.CONFIRMATION_QUESTION, questionType, "");
    } else {
        // find callback for this question
        while (questions.hasNext()) {
            mapQuestion = (String) questions.next();

            if (StringUtils.equals(mapQuestion, question)) {
                callback = questionsAndCallbacks.get(mapQuestion);
                break;
            }
        }
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, mapQuestion);

        Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
        if (question.equals(mapQuestion) && buttonClicked.equals(ConfirmationQuestion.NO)) {
            // If 'No' is the button clicked, just reload the doc

            String nextQuestion = null;
            // ask another question if more left
            if (questions.hasNext()) {
                nextQuestion = (String) questions.next();
                key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, nextQuestion);

                return this.performQuestionWithInput(mapping, form, request, response, nextQuestion, key,
                        OLEConstants.CONFIRMATION_QUESTION, questionType, "");
            } else {

                return mapping.findForward(OLEConstants.MAPPING_BASIC);
            }
        }
        // Have to check length on value entered.
        String introNoteMessage = notePrefix + OLEConstants.BLANK_SPACE;

        // Build out full message.
        noteText = introNoteMessage + reason;
        int noteTextLength = noteText.length();

        // Get note text max length from DD.
        int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeMaxLength(Note.class, OLEConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
        if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
            // Figure out exact number of characters that the user can enter.
            int reasonLimit = noteTextMaxLength - noteTextLength;
            if (reason == null) {
                // Prevent a NPE by setting the reason to a blank string.
                reason = "";
            }

            return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response,
                    mapQuestion, key, OLEConstants.CONFIRMATION_QUESTION, questionType, "", reason,
                    PurapKeyConstants.ERROR_PAYMENT_REQUEST_REASON_REQUIRED,
                    OLEConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString());
        }
    }

    // make callback
    if (ObjectUtils.isNotNull(callback)) {
        ReceivingDocument refreshedReceivingDocument = callback.doPostQuestion(receivingDocument, noteText);
        kualiDocumentFormBase.setDocument(refreshedReceivingDocument);
    }
    String nextQuestion = null;
    // ask another question if more left
    if (questions.hasNext()) {
        nextQuestion = (String) questions.next();
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, nextQuestion);

        return this.performQuestionWithInput(mapping, form, request, response, nextQuestion, key,
                OLEConstants.CONFIRMATION_QUESTION, questionType, "");
    }

    return redirect;
}

From source file:org.kuali.kfs.module.purap.document.web.struts.ReceivingBaseAction.java

/**
 * Builds and asks questions which require text input by the user for a payment request or a credit memo.
 * //from   w  w w . java 2s .com
 * @param mapping An ActionMapping
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @param questionType A String used to distinguish which question is being asked
 * @param notePrefix A String explaining what action was taken, to be prepended to the note containing the reason, which gets
 *        written to the document
 * @param operation A one-word String description of the action to be taken, to be substituted into the message. (Can be an
 *        empty String for some messages.)
 * @param messageKey A (whole) key to the message which will appear on the question screen
 * @param questionsAndCallbacks A TreeMap associating the type of question to be asked and the type of callback which should
 *        happen in that case
 * @param messagePrefix The most general part of a key to a message text to be retrieved from ConfigurationService,
 *        Describes a collection of questions.
 * @param redirect An ActionForward to return to if done with questions
 * @return An ActionForward
 * @throws Exception
 */
protected ActionForward askQuestionWithInput(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String questionType, String notePrefix, String operation,
        String messageKey, TreeMap<String, ReceivingQuestionCallback> questionsAndCallbacks,
        String messagePrefix, ActionForward redirect) throws Exception {
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
    ReceivingDocument receivingDocument = (ReceivingDocument) kualiDocumentFormBase.getDocument();

    String question = (String) request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
    String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
    String noteText = "";

    ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
    String firstQuestion = questionsAndCallbacks.firstKey();
    ReceivingQuestionCallback callback = null;
    Iterator questions = questionsAndCallbacks.keySet().iterator();
    String mapQuestion = null;
    String key = null;

    // Start in logic for confirming the close.
    if (question == null) {
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, firstQuestion);
        String message = StringUtils.replace(key, "{0}", operation);

        // Ask question if not already asked.
        return this.performQuestionWithInput(mapping, form, request, response, firstQuestion, message,
                KFSConstants.CONFIRMATION_QUESTION, questionType, "");
    } else {
        // find callback for this question
        while (questions.hasNext()) {
            mapQuestion = (String) questions.next();

            if (StringUtils.equals(mapQuestion, question)) {
                callback = questionsAndCallbacks.get(mapQuestion);
                break;
            }
        }
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, mapQuestion);

        Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
        if (question.equals(mapQuestion) && buttonClicked.equals(ConfirmationQuestion.NO)) {
            // If 'No' is the button clicked, just reload the doc

            String nextQuestion = null;
            // ask another question if more left
            if (questions.hasNext()) {
                nextQuestion = (String) questions.next();
                key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, nextQuestion);

                return this.performQuestionWithInput(mapping, form, request, response, nextQuestion, key,
                        KFSConstants.CONFIRMATION_QUESTION, questionType, "");
            } else {

                return mapping.findForward(KFSConstants.MAPPING_BASIC);
            }
        }
        // Have to check length on value entered.
        String introNoteMessage = notePrefix + KFSConstants.BLANK_SPACE;

        // Build out full message.
        noteText = introNoteMessage + reason;
        int noteTextLength = noteText.length();

        // Get note text max length from DD.
        int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeMaxLength(Note.class, KFSConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
        if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
            // Figure out exact number of characters that the user can enter.
            int reasonLimit = noteTextMaxLength - noteTextLength;
            if (reason == null) {
                // Prevent a NPE by setting the reason to a blank string.
                reason = "";
            }

            return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response,
                    mapQuestion, key, KFSConstants.CONFIRMATION_QUESTION, questionType, "", reason,
                    PurapKeyConstants.ERROR_PAYMENT_REQUEST_REASON_REQUIRED,
                    KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString());
        }
    }

    // make callback
    if (ObjectUtils.isNotNull(callback)) {
        ReceivingDocument refreshedReceivingDocument = callback.doPostQuestion(receivingDocument, noteText);
        kualiDocumentFormBase.setDocument(refreshedReceivingDocument);
    }
    String nextQuestion = null;
    // ask another question if more left
    if (questions.hasNext()) {
        nextQuestion = (String) questions.next();
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, nextQuestion);

        return this.performQuestionWithInput(mapping, form, request, response, nextQuestion, key,
                KFSConstants.CONFIRMATION_QUESTION, questionType, "");
    }

    return redirect;
}

From source file:com.sec.ose.osi.report.standard.data.BillOfMaterialsRowGenerator.java

private String getFileCountForFolders(ArrayList<IdentifiedFilesRow> fileEntList) {

    TreeMap<String, Integer> map = new TreeMap<String, Integer>(); // parent path, value

    if (fileEntList == null || fileEntList.size() == 0)
        return "<None>";

    for (IdentifiedFilesRow ent : fileEntList) {
        String parentPath = (new File(ent.getFullPath())).getParent();
        if (parentPath == null)
            parentPath = "";

        if (map.containsKey(parentPath) == false) {
            map.put(parentPath, 0);//w  w w  .  j  ava2 s  .  c  om
        }

        map.put(parentPath, map.get(parentPath) + 1);
    }

    if (map.size() == 0)
        return "";
    if (map.size() == 1)
        return ("(" + map.get(map.firstKey()) + " files)\n");

    String msg = "";
    for (String path : map.keySet()) {
        msg += path;
        if (!path.endsWith("/"))
            msg += "/ ";
        msg += "(" + map.get(path) + " files)\n";
    }
    msg = msg.replace("\\", "/");

    if (msg.length() > 0) {
        return msg.substring(0, msg.length() - 1);
    }

    return "";
}

From source file:com.irccloud.android.data.EventsDataSource.java

public void pruneEvents(int bid) {
    synchronized (events) {
        TreeMap<Long, Event> e = events.get(bid);
        while (e != null && e.size() > 50 && e.firstKey() != null) {
            e.remove(e.firstKey());//w w w. j a va 2  s .c  o m
        }
    }
}