de.fischer.thotti.reportgen.combiner.MedianIterator.java Source code

Java tutorial

Introduction

Here is the source code for de.fischer.thotti.reportgen.combiner.MedianIterator.java

Source

/*
 * Copyright 2012 Oliver B. Fischer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.fischer.thotti.reportgen.combiner;

import de.fischer.thotti.persistence.NDResultEntity;
import de.fischer.thotti.reportgen.diagram.DatePoint;
import org.apache.commons.lang3.time.DateUtils;

import java.util.*;

public class MedianIterator extends AbstractDayCombinerIterator<DatePoint> {
    private TreeSet<NDResultEntity> elements = new TreeSet<NDResultEntity>(new SortByDuration());

    public MedianIterator(Iterator<NDResultEntity> source) {
        super(source);
    }

    @Override
    void processNextInputElement(NDResultEntity nextElement) {
        elements.add(nextElement);
    }

    @Override
    DatePoint getNextElementComputed() {
        double medianValue;
        int numOfValues = elements.size();
        int remainder = numOfValues % 2;
        int idxFirstElementAboveMedian = ((numOfValues - remainder) / 2) - 1
                - 1 /* Adjustment for 0 based index of collections. */;

        System.out.println("E: " + elements.size());
        System.out.println("R: " + remainder);

        Iterator<NDResultEntity> itr = elements.iterator();

        for (int index = 0; index <= idxFirstElementAboveMedian; index++) {
            itr.next();
        }

        NDResultEntity firstAboveMedian = itr.next();
        double executionTimeA = firstAboveMedian.getExecutionTime();

        if (numOfValues == 1) {
            medianValue = executionTimeA;

        } else {
            NDResultEntity firstBelowMedian = itr.next();

            double executionTimeB = firstBelowMedian.getExecutionTime();
            medianValue = (executionTimeA + executionTimeB) / 2;
        }

        DatePoint result = new DatePoint();

        Date date = DateUtils.truncate(firstAboveMedian.getStartedAt(), Calendar.DAY_OF_MONTH);
        result.setPointInTime(date);
        result.setValue(medianValue);

        return result;
    }

    @Override
    void prepareNextComputation() {

        elements.clear();

    }

    private static class SortByDuration implements Comparator<NDResultEntity> {
        @Override
        public int compare(NDResultEntity o1, NDResultEntity o2) {
            return o1.getStartedAt().compareTo(o2.getStartedAt());
        }
    }
}