Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

In this page you can find the example usage for java.text NumberFormat setMaximumFractionDigits.

Prototype

public void setMaximumFractionDigits(int newValue) 

Source Link

Document

Sets the maximum number of digits allowed in the fraction portion of a number.

Usage

From source file:org.red5.io.mp4.impl.MP4Reader.java

/**
 * This handles the moov atom being at the beginning or end of the file, so the mdat may also be before or after the moov atom.
 *//*from  www  . j  a va  2 s. c  om*/
public void decodeHeader() {
    try {
        // we want a moov and an mdat, anything else will throw the invalid file type error
        MovieBox moov = isoFile.getBoxes(MovieBox.class).get(0);
        if (log.isDebugEnabled()) {
            log.debug("moov children: {}", moov.getBoxes().size());
            dumpBox(moov);
        }
        // get the movie header
        MovieHeaderBox mvhd = moov.getMovieHeaderBox();
        // get the timescale and duration
        timeScale = mvhd.getTimescale();
        duration = mvhd.getDuration();
        log.debug("Time scale {} Duration {}", timeScale, duration);
        double lengthInSeconds = (double) duration / timeScale;
        log.debug("Seconds {}", lengthInSeconds);
        // look at the tracks
        log.debug("Tracks: {}", moov.getTrackCount());
        List<TrackBox> tracks = moov.getBoxes(TrackBox.class); // trak
        for (TrackBox trak : tracks) {
            if (log.isDebugEnabled()) {
                log.debug("trak children: {}", trak.getBoxes().size());
                dumpBox(trak);
            }
            TrackHeaderBox tkhd = trak.getTrackHeaderBox(); // tkhd
            log.debug("Track id: {}", tkhd.getTrackId());
            if (tkhd != null && tkhd.getWidth() > 0) {
                width = (int) tkhd.getWidth();
                height = (int) tkhd.getHeight();
                log.debug("Width {} x Height {}", width, height);
            }
            MediaBox mdia = trak.getMediaBox(); // mdia
            long scale = 0;
            boolean isAudio = false, isVideo = false;
            if (mdia != null) {
                if (log.isDebugEnabled()) {
                    log.debug("mdia children: {}", mdia.getBoxes().size());
                    dumpBox(mdia);
                }
                MediaHeaderBox mdhd = mdia.getMediaHeaderBox(); // mdhd
                if (mdhd != null) {
                    log.debug("Media data header atom found");
                    // this will be for either video or audio depending media info
                    scale = mdhd.getTimescale();
                    log.debug("Time scale {}", scale);
                }
                HandlerBox hdlr = mdia.getHandlerBox(); // hdlr
                if (hdlr != null) {
                    String hdlrType = hdlr.getHandlerType();
                    if ("vide".equals(hdlrType)) {
                        hasVideo = true;
                        if (scale > 0) {
                            videoTimeScale = scale * 1.0;
                            log.debug("Video time scale: {}", videoTimeScale);
                        }
                    } else if ("soun".equals(hdlrType)) {
                        hasAudio = true;
                        if (scale > 0) {
                            audioTimeScale = scale * 1.0;
                            log.debug("Audio time scale: {}", audioTimeScale);
                        }
                    } else {
                        log.debug("Unhandled handler type: {}", hdlrType);
                    }
                }
                MediaInformationBox minf = mdia.getMediaInformationBox();
                if (minf != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("minf children: {}", minf.getBoxes().size());
                        dumpBox(minf);
                    }
                    AbstractMediaHeaderBox abs = minf.getMediaHeaderBox();
                    if (abs != null) {
                        if (abs instanceof SoundMediaHeaderBox) { // smhd
                            //SoundMediaHeaderBox smhd = (SoundMediaHeaderBox) abs;
                            log.debug("Sound header atom found");
                            isAudio = true;
                        } else if (abs instanceof VideoMediaHeaderBox) { // vmhd
                            //VideoMediaHeaderBox vmhd = (VideoMediaHeaderBox) abs;
                            log.debug("Video header atom found");
                            isVideo = true;
                        } else {
                            log.debug("Unhandled media header box: {}", abs.getType());
                        }
                    } else {
                        log.debug("Null media header box");
                    }
                }
            }
            SampleTableBox stbl = trak.getSampleTableBox(); // mdia/minf/stbl
            if (stbl != null) {
                if (log.isDebugEnabled()) {
                    log.debug("stbl children: {}", stbl.getBoxes().size());
                    dumpBox(stbl);
                }
                SampleDescriptionBox stsd = stbl.getSampleDescriptionBox(); // stsd
                if (stsd != null) {
                    //stsd: mp4a, avc1, mp4v
                    //String type = stsd.getType();
                    if (log.isDebugEnabled()) {
                        log.debug("stsd children: {}", stsd.getBoxes().size());
                        dumpBox(stsd);
                    }
                    SampleEntry entry = stsd.getSampleEntry();
                    if (entry != null) {
                        log.debug("Sample entry type: {}", entry.getType());
                        // determine if audio or video and process from there
                        if (entry instanceof AudioSampleEntry) {
                            processAudioBox(stbl, (AudioSampleEntry) entry, scale);
                        } else if (entry instanceof VisualSampleEntry) {
                            processVideoBox(stbl, (VisualSampleEntry) entry, scale);
                        }
                    } else {
                        log.debug("Sample entry was null");
                        if (isVideo) {
                            processVideoBox(stbl, scale);
                        } else if (isAudio) {
                            processAudioBox(stbl, scale);
                        }
                    }
                }
            }
        }
        //calculate FPS
        fps = (videoSampleCount * timeScale) / (double) duration;
        log.debug("FPS calc: ({} * {}) / {}", new Object[] { videoSampleCount, timeScale, duration });
        log.debug("FPS: {}", fps);
        //real duration
        StringBuilder sb = new StringBuilder();
        double videoTime = ((double) duration / (double) timeScale);
        log.debug("Video time: {}", videoTime);
        int minutes = (int) (videoTime / 60);
        if (minutes > 0) {
            sb.append(minutes);
            sb.append('.');
        }
        //formatter for seconds / millis
        NumberFormat df = DecimalFormat.getInstance();
        df.setMaximumFractionDigits(2);
        sb.append(df.format((videoTime % 60)));
        formattedDuration = sb.toString();
        log.debug("Time: {}", formattedDuration);

        List<MediaDataBox> mdats = isoFile.getBoxes(MediaDataBox.class);
        if (mdats != null && !mdats.isEmpty()) {
            log.debug("mdat count: {}", mdats.size());
            MediaDataBox mdat = mdats.get(0);
            if (mdat != null) {
                mdatOffset = mdat.getOffset();
            }
        }
        //log.debug("Offsets - moov: {} mdat: {}", moovOffset, mdatOffset);
        log.debug("Offset - mdat: {}", mdatOffset);

        // handle fragmentation
        boolean fragmented = false;
        // detect whether or not this movie contains fragments first
        List<MovieFragmentBox> moofs = isoFile.getBoxes(MovieFragmentBox.class); // moof
        if (moofs != null && !moofs.isEmpty()) {
            log.info("Movie contains {} framents", moofs.size());
            fragmented = true;
            for (MovieFragmentBox moof : moofs) {
                dumpBox(moof);
                MovieFragmentHeaderBox mfhd = moof.getBoxes(MovieFragmentHeaderBox.class).get(0);
                if (mfhd != null) {
                    log.debug("Sequence: {} path: {}", mfhd.getSequenceNumber(), mfhd.getPath());
                }
                List<TrackFragmentBox> trafs = moof.getBoxes(TrackFragmentBox.class);
                for (TrackFragmentBox traf : trafs) {
                    TrackFragmentHeaderBox tfhd = traf.getTrackFragmentHeaderBox();
                    log.debug("tfhd: {}", tfhd);
                }
                List<TrackExtendsBox> trexs = moof.getBoxes(TrackExtendsBox.class);
                for (TrackExtendsBox trex : trexs) {
                    log.debug("trex - track id: {} duration: {} sample size: {}", trex.getTrackId(),
                            trex.getDefaultSampleDuration(), trex.getDefaultSampleSize());
                }
                //List<Long> syncSamples = moof.getSyncSamples(sdtp);
                if (compositionTimes == null) {
                    compositionTimes = new ArrayList<CompositionTimeToSample.Entry>();
                }
                LinkedList<Integer> dataOffsets = new LinkedList<Integer>();
                LinkedList<Long> sampleSizes = new LinkedList<Long>();
                List<TrackRunBox> truns = moof.getTrackRunBoxes();
                log.info("Fragment contains {} TrackRunBox entries", truns.size());
                for (TrackRunBox trun : truns) {
                    log.debug("trun - {}", trun);
                    //videoSamplesToChunks
                    if (trun.isDataOffsetPresent()) {
                        dataOffsets.add(trun.getDataOffset());
                    }
                    videoSampleCount += trun.getSampleCount();
                    List<TrackRunBox.Entry> recs = trun.getEntries();
                    log.info("TrackRunBox contains {} entries", recs.size());
                    for (TrackRunBox.Entry rec : recs) {
                        log.info("Entry: {}", rec);
                        if (trun.isSampleCompositionTimeOffsetPresent()) {
                            CompositionTimeToSample.Entry ctts = new CompositionTimeToSample.Entry(
                                    (int) trun.getSampleCount(), (int) rec.getSampleCompositionTimeOffset());
                            compositionTimes.add(ctts);
                        }
                        sampleSizes.add(rec.getSampleSize());
                        if (trun.isSampleDurationPresent()) {
                            videoSampleDuration += rec.getSampleDuration();
                        }
                    }
                }
                // SampleToChunkBox.Entry

                log.info("Video duration: {}", videoSampleDuration);
                videoSamples = new long[sampleSizes.size()];
                for (int i = 0; i < videoSamples.length; i++) {
                    videoSamples[i] = sampleSizes.remove();
                }
                log.info("Video samples: {}", Arrays.toString(videoSamples));
                videoChunkOffsets = new long[dataOffsets.size()];
                for (int i = 0; i < videoChunkOffsets.length; i++) {
                    videoChunkOffsets[i] = dataOffsets.remove();
                }
                log.info("Video chunk offsets: {}", Arrays.toString(videoChunkOffsets));
            }
        }
        if (isoFile.getBoxes(MovieFragmentRandomAccessBox.class).size() > 0) { // mfra
            log.info("Movie contains frament random access info");
        }
        if (isoFile.getBoxes(ActionMessageFormat0SampleEntryBox.class).size() > 0) {
            log.info("Movie contains AMF entries");
        }
        // if we have fragments, we should have an mvex
        if (fragmented) {
            MovieExtendsBox mvex = moov.getBoxes(MovieExtendsBox.class).get(0); // mvex
            dumpBox(mvex);
            List<TrackExtendsBox> trexs = mvex.getBoxes(TrackExtendsBox.class);
            for (TrackExtendsBox trex : trexs) {
                log.debug("trex - track id: {} duration: {} sample size: {}", trex.getTrackId(),
                        trex.getDefaultSampleDuration(), trex.getDefaultSampleSize());
            }
        }
    } catch (Exception e) {
        log.error("Exception decoding header / atoms", e);
    }
}

From source file:org.slc.sli.dashboard.manager.impl.PopulationManagerImpl.java

@Override
@LogExecutionTime//from  w  w w  .j ava  2 s  .c om
public GenericEntity getAttendance(String token, Object studentIdObj, Config.Data config) {
    // get yearsBack from param
    String yearsBack = config.getParams() == null ? null : (String) config.getParams().get("yearsBack");
    int intYearsBack = DEFAULT_YEARS_BACK;
    if (yearsBack != null) {
        try {
            intYearsBack = Integer.parseInt(yearsBack);
        } catch (NumberFormatException e) {
            LOG.error("params: value of yearsBack was not integer. [" + intYearsBack
                    + "]. Using default value [" + DEFAULT_YEARS_BACK + "]");
            intYearsBack = DEFAULT_YEARS_BACK;
        }
    }

    GenericEntity attendance = new GenericEntity();
    String studentId = (String) studentIdObj;
    // get Enrollment History
    List<GenericEntity> enrollments = getApiClient().getEnrollmentForStudent(token, studentId);

    // creating lookup index for enrollment, key is term (yyyy-yyyy)
    int currentSchoolYear = 0;
    Map<String, LinkedHashMap<String, Object>> enrollmentsIndex = new HashMap<String, LinkedHashMap<String, Object>>();
    for (LinkedHashMap<String, Object> enrollment : enrollments) {
        String entryDateYear = "";
        String exitWithdrawDateYear = "";
        String entryDate = (String) enrollment.get(Constants.ATTR_ENROLLMENT_ENTRY_DATE);
        String exitWithdrawDate = (String) enrollment.get(Constants.ATTR_ENROLLMENT_EXIT_WITHDRAW_DATE);

        // find a year for entryDate
        if (entryDate != null && entryDate.length() > 3) {
            entryDateYear = entryDate.substring(0, 4);
        }

        // find a year for exitWithdarwDate
        if (exitWithdrawDate != null && exitWithdrawDate.length() > 3) {
            exitWithdrawDateYear = exitWithdrawDate.substring(0, 4);
        } else {
            // exitWithdrawDate is null because it is in current term.
            // add one year to entryDateYear.
            currentSchoolYear = Integer.parseInt(entryDateYear);
            exitWithdrawDateYear = Integer.toString(currentSchoolYear + 1);
        }

        // creating index lookup key
        String key = entryDateYear + "-" + exitWithdrawDateYear;

        enrollmentsIndex.put(key, enrollment);
    }

    // Numberformat for %Present - no fraction
    NumberFormat numberFormat = NumberFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(0);

    // get attendance for the student
    List<GenericEntity> attendanceList = this.getStudentAttendance(token, studentId, null, null);
    for (Map<String, Object> targetAttendance : attendanceList) {

        // get schoolYearAttendance
        List<Map<String, Object>> schoolYearAttendances = (List<Map<String, Object>>) targetAttendance
                .get(Constants.ATTR_ATTENDANCE_SCHOOLYEAR_ATTENDANCE);
        if (schoolYearAttendances != null) {

            // sort by schoolYear
            GenericEntityComparator comparator = new GenericEntityComparator(Constants.ATTR_SCHOOL_YEAR,
                    String.class);
            Collections.sort(schoolYearAttendances, Collections.reverseOrder(comparator));

            for (Map<String, Object> schoolYearAttendance : schoolYearAttendances) {
                int inAttendanceCount = 0;
                int absenceCount = 0;
                int excusedAbsenceCount = 0;
                int unexcusedAbsenceCount = 0;
                int tardyCount = 0;
                int earlyDepartureCount = 0;
                int totalCount = 0;

                // get schoolYear
                String schoolYear = (String) schoolYearAttendance.get(Constants.ATTR_SCHOOL_YEAR);

                // if some reasons we cannot find currentSchoolYear, then
                // display all histories
                // if intYearsBack is not set to NO_LIMIT (-1) and found
                // currentSchoolYear,
                // then exam whether current loop is within user defined
                // yearsBack
                if (intYearsBack != NO_LIMIT && currentSchoolYear != 0) {
                    int targetYear = Integer.parseInt(schoolYear.substring(0, 4));
                    // if yearsBack is 1, it means current schoolYear.
                    // break from the loop if currentSchoolYear-targetYear
                    // is over yearsBack.
                    if ((currentSchoolYear - targetYear) >= intYearsBack) {
                        break;
                    }
                }

                // get target school year enrollment
                LinkedHashMap<String, Object> enrollment = enrollmentsIndex.get(schoolYear);
                GenericEntity currentTermAttendance = new GenericEntity();

                // set school term
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_TERM, schoolYear);

                String nameOfInstitution = "";
                boolean enrollmentExistsForAttendance = false;

                // get school name from enrollment
                if (enrollment != null) {
                    Map<String, Object> school = (Map<String, Object>) enrollment.get(Constants.ATTR_SCHOOL);
                    if (school != null) {
                        nameOfInstitution = (String) school.get(Constants.ATTR_NAME_OF_INST);
                    }
                    String enrollmentSchoolId = (String) enrollment.get(Constants.ATTR_SCHOOL_ID);
                    String attendanceSchoolId = (String) targetAttendance.get(Constants.ATTR_SCHOOL_ID);
                    if (enrollmentSchoolId.equals(attendanceSchoolId) == true) {
                        // only show attendances that are for the school in the
                        // target enrollment
                        enrollmentExistsForAttendance = true;
                    }

                }

                // get attendanceEvent
                List<LinkedHashMap<String, Object>> attendanceEvents = (List<LinkedHashMap<String, Object>>) schoolYearAttendance
                        .get(Constants.ATTR_ATTENDANCE_ATTENDANCE_EVENT);

                // count each attendance event
                if (attendanceEvents != null && enrollmentExistsForAttendance) {
                    for (Map<String, Object> attendanceEvent : attendanceEvents) {
                        String event = (String) attendanceEvent.get(Constants.ATTR_ATTENDANCE_EVENT_CATEGORY);
                        if (event != null) {
                            totalCount++;
                            if (event.equals(Constants.ATTR_ATTENDANCE_IN_ATTENDANCE)) {
                                inAttendanceCount++;
                            } else if (event.equals(Constants.ATTR_ATTENDANCE_ABSENCE)) {
                                absenceCount++;
                            } else if (event.equals(Constants.ATTR_ATTENDANCE_EXCUSED_ABSENCE)) {
                                excusedAbsenceCount++;
                            } else if (event.equals(Constants.ATTR_ATTENDANCE_UNEXCUSED_ABSENCE)) {
                                unexcusedAbsenceCount++;
                            } else if (event.equals(Constants.ATTR_ATTENDANCE_TARDY)) {
                                tardyCount++;
                            } else if (event.equals(Constants.ATTR_ATTENDANCE_EARLY_DEPARTURE)) {
                                earlyDepartureCount++;
                            }
                        }
                    }
                }

                // set school name
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_SCHOOL, nameOfInstitution);

                String gradeLevel = "";
                // set grade level
                if (enrollment != null) {
                    gradeLevel = (String) enrollment.get(Constants.ATTR_ENROLLMENT_ENTRY_GRADE_LEVEL_CODE);
                }
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_GRADE_LEVEL, gradeLevel);

                // set %Present
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_PRESENT,
                        numberFormat.format(totalCount == 0 ? 0
                                : ((inAttendanceCount + tardyCount + earlyDepartureCount) / (double) totalCount)
                                        * 100));
                // set In Attendance
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_IN_ATTENDANCE, inAttendanceCount);

                // set Total Absences
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_TOTAL_ABSENCES,
                        absenceCount + excusedAbsenceCount + unexcusedAbsenceCount);

                // set Absence
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_ABSENCE, absenceCount);

                // set Excused Absences
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_EXCUSED, excusedAbsenceCount);

                // set Unexcused Absences
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_UNEXCUSED, unexcusedAbsenceCount);

                // set Tardy
                currentTermAttendance.put(Constants.ATTENDANCE_HISTORY_TARDY, tardyCount);

                // set Early departure
                currentTermAttendance.put(Constants.ATTENDANCE_EARLY_DEPARTURE, earlyDepartureCount);

                // Add to attendance list
                attendance.appendToList("attendance", currentTermAttendance);
            }
        }
    }
    return attendance;
}

From source file:fr.hoteia.qalingo.core.web.util.impl.RequestUtilImpl.java

/**
 *
 *//*from www .  j  a va2s . c o m*/
public NumberFormat getNumberFormat(final RequestData requestData, final String currencyCode,
        final RoundingMode roundingMode, final int maximumFractionDigits, final int minimumFractionDigits,
        final int maximumIntegerDigits, final int minimumIntegerDigits) throws Exception {
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();
    NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
    formatter.setGroupingUsed(true);
    formatter.setParseIntegerOnly(false);
    formatter.setRoundingMode(roundingMode);
    Currency currency = Currency.getInstance(currencyCode);
    formatter.setCurrency(currency);

    formatter.setMaximumFractionDigits(maximumFractionDigits);
    formatter.setMinimumFractionDigits(minimumFractionDigits);

    formatter.setMaximumIntegerDigits(maximumIntegerDigits);
    formatter.setMinimumIntegerDigits(minimumIntegerDigits);

    return formatter;
}

From source file:org.red5.io.mp4.MP4Reader.java

/**
 * This handles the moov atom being at the beginning or end of the file, so the mdat may also
 * be before or after the moov atom./*from   ww w . j  a v a 2s. c o m*/
 */
public void decodeHeader() {
    try {
        // the first atom will/should be the type
        MP4Atom type = MP4Atom.createAtom(fis);
        // expect ftyp
        log.debug("Type {}", MP4Atom.intToType(type.getType()));
        //log.debug("Atom int types - free={} wide={}", MP4Atom.typeToInt("free"), MP4Atom.typeToInt("wide"));
        // keep a running count of the number of atoms found at the "top" levels
        int topAtoms = 0;
        // we want a moov and an mdat, anything else throw the invalid file type error
        while (topAtoms < 2) {
            MP4Atom atom = MP4Atom.createAtom(fis);
            switch (atom.getType()) {
            case 1836019574: //moov
                topAtoms++;
                MP4Atom moov = atom;
                // expect moov
                log.debug("Type {}", MP4Atom.intToType(moov.getType()));
                log.debug("moov children: {}", moov.getChildren());
                moovOffset = fis.getOffset() - moov.getSize();

                MP4Atom mvhd = moov.lookup(MP4Atom.typeToInt("mvhd"), 0);
                if (mvhd != null) {
                    log.debug("Movie header atom found");
                    //get the initial timescale
                    timeScale = mvhd.getTimeScale();
                    duration = mvhd.getDuration();
                    log.debug("Time scale {} Duration {}", timeScale, duration);
                }

                /* nothing needed here yet
                MP4Atom meta = moov.lookup(MP4Atom.typeToInt("meta"), 0);
                if (meta != null) {
                   log.debug("Meta atom found");
                   log.debug("{}", ToStringBuilder.reflectionToString(meta));
                }
                */

                //we would like to have two tracks, but it shouldn't be a requirement
                int loops = 0;
                int tracks = 0;
                do {

                    MP4Atom trak = moov.lookup(MP4Atom.typeToInt("trak"), loops);
                    if (trak != null) {
                        log.debug("Track atom found");
                        log.debug("trak children: {}", trak.getChildren());
                        // trak: tkhd, edts, mdia
                        MP4Atom tkhd = trak.lookup(MP4Atom.typeToInt("tkhd"), 0);
                        if (tkhd != null) {
                            log.debug("Track header atom found");
                            log.debug("tkhd children: {}", tkhd.getChildren());
                            if (tkhd.getWidth() > 0) {
                                width = tkhd.getWidth();
                                height = tkhd.getHeight();
                                log.debug("Width {} x Height {}", width, height);
                            }
                        }

                        MP4Atom edts = trak.lookup(MP4Atom.typeToInt("edts"), 0);
                        if (edts != null) {
                            log.debug("Edit atom found");
                            log.debug("edts children: {}", edts.getChildren());
                            //log.debug("Width {} x Height {}", edts.getWidth(), edts.getHeight());
                        }

                        MP4Atom mdia = trak.lookup(MP4Atom.typeToInt("mdia"), 0);
                        if (mdia != null) {
                            log.debug("Media atom found");
                            // mdia: mdhd, hdlr, minf

                            int scale = 0;
                            //get the media header atom
                            MP4Atom mdhd = mdia.lookup(MP4Atom.typeToInt("mdhd"), 0);
                            if (mdhd != null) {
                                log.debug("Media data header atom found");
                                //this will be for either video or audio depending media info
                                scale = mdhd.getTimeScale();
                                log.debug("Time scale {}", scale);
                            }

                            MP4Atom hdlr = mdia.lookup(MP4Atom.typeToInt("hdlr"), 0);
                            if (hdlr != null) {
                                log.debug("Handler ref atom found");
                                // soun or vide
                                log.debug("Handler type: {}", MP4Atom.intToType(hdlr.getHandlerType()));
                                String hdlrType = MP4Atom.intToType(hdlr.getHandlerType());
                                if ("vide".equals(hdlrType)) {
                                    hasVideo = true;
                                    if (scale > 0) {
                                        videoTimeScale = scale * 1.0;
                                        log.debug("Video time scale: {}", videoTimeScale);
                                    }
                                } else if ("soun".equals(hdlrType)) {
                                    hasAudio = true;
                                    if (scale > 0) {
                                        audioTimeScale = scale * 1.0;
                                        log.debug("Audio time scale: {}", audioTimeScale);
                                    }
                                }
                                tracks++;
                            }

                            MP4Atom minf = mdia.lookup(MP4Atom.typeToInt("minf"), 0);
                            if (minf != null) {
                                log.debug("Media info atom found");
                                // minf: (audio) smhd, dinf, stbl / (video) vmhd,
                                // dinf, stbl

                                MP4Atom smhd = minf.lookup(MP4Atom.typeToInt("smhd"), 0);
                                if (smhd != null) {
                                    log.debug("Sound header atom found");
                                    MP4Atom dinf = minf.lookup(MP4Atom.typeToInt("dinf"), 0);
                                    if (dinf != null) {
                                        log.debug("Data info atom found");
                                        // dinf: dref
                                        log.debug("Sound dinf children: {}", dinf.getChildren());
                                        MP4Atom dref = dinf.lookup(MP4Atom.typeToInt("dref"), 0);
                                        if (dref != null) {
                                            log.debug("Data reference atom found");
                                        }

                                    }
                                    MP4Atom stbl = minf.lookup(MP4Atom.typeToInt("stbl"), 0);
                                    if (stbl != null) {
                                        log.debug("Sample table atom found");
                                        // stbl: stsd, stts, stss, stsc, stsz, stco,
                                        // stsh
                                        log.debug("Sound stbl children: {}", stbl.getChildren());
                                        // stsd - sample description
                                        // stts - time to sample
                                        // stsc - sample to chunk
                                        // stsz - sample size
                                        // stco - chunk offset

                                        //stsd - has codec child
                                        MP4Atom stsd = stbl.lookup(MP4Atom.typeToInt("stsd"), 0);
                                        if (stsd != null) {
                                            //stsd: mp4a
                                            log.debug("Sample description atom found");
                                            MP4Atom mp4a = stsd.getChildren().get(0);
                                            //could set the audio codec here
                                            setAudioCodecId(MP4Atom.intToType(mp4a.getType()));
                                            //log.debug("{}", ToStringBuilder.reflectionToString(mp4a));
                                            log.debug("Sample size: {}", mp4a.getSampleSize());
                                            int ats = mp4a.getTimeScale();
                                            //skip invalid audio time scale
                                            if (ats > 0) {
                                                audioTimeScale = ats * 1.0;
                                            }
                                            audioChannels = mp4a.getChannelCount();
                                            log.debug("Sample rate (audio time scale): {}", audioTimeScale);
                                            log.debug("Channels: {}", audioChannels);
                                            //mp4a: esds
                                            if (mp4a.getChildren().size() > 0) {
                                                log.debug("Elementary stream descriptor atom found");
                                                MP4Atom esds = mp4a.getChildren().get(0);
                                                log.debug("{}", ToStringBuilder.reflectionToString(esds));
                                                MP4Descriptor descriptor = esds.getEsd_descriptor();
                                                log.debug("{}", ToStringBuilder.reflectionToString(descriptor));
                                                if (descriptor != null) {
                                                    Vector<MP4Descriptor> children = descriptor.getChildren();
                                                    for (int e = 0; e < children.size(); e++) {
                                                        MP4Descriptor descr = children.get(e);
                                                        log.debug("{}",
                                                                ToStringBuilder.reflectionToString(descr));
                                                        if (descr.getChildren().size() > 0) {
                                                            Vector<MP4Descriptor> children2 = descr
                                                                    .getChildren();
                                                            for (int e2 = 0; e2 < children2.size(); e2++) {
                                                                MP4Descriptor descr2 = children2.get(e2);
                                                                log.debug("{}", ToStringBuilder
                                                                        .reflectionToString(descr2));
                                                                if (descr2
                                                                        .getType() == MP4Descriptor.MP4DecSpecificInfoDescriptorTag) {
                                                                    //we only want the MP4DecSpecificInfoDescriptorTag
                                                                    audioDecoderBytes = descr2.getDSID();
                                                                    //compare the bytes to get the aacaot/aottype 
                                                                    //match first byte
                                                                    switch (audioDecoderBytes[0]) {
                                                                    case 0x12:
                                                                    default:
                                                                        //AAC LC - 12 10
                                                                        audioCodecType = 1;
                                                                        break;
                                                                    case 0x0a:
                                                                        //AAC Main - 0A 10
                                                                        audioCodecType = 0;
                                                                        break;
                                                                    case 0x11:
                                                                    case 0x13:
                                                                        //AAC LC SBR - 11 90 & 13 xx
                                                                        audioCodecType = 2;
                                                                        break;
                                                                    }
                                                                    //we want to break out of top level for loop
                                                                    e = 99;
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        //stsc - has Records
                                        MP4Atom stsc = stbl.lookup(MP4Atom.typeToInt("stsc"), 0);
                                        if (stsc != null) {
                                            log.debug("Sample to chunk atom found");
                                            audioSamplesToChunks = stsc.getRecords();
                                            log.debug("Record count: {}", audioSamplesToChunks.size());
                                            MP4Atom.Record rec = audioSamplesToChunks.firstElement();
                                            log.debug("Record data: Description index={} Samples per chunk={}",
                                                    rec.getSampleDescriptionIndex(), rec.getSamplesPerChunk());
                                        }
                                        //stsz - has Samples
                                        MP4Atom stsz = stbl.lookup(MP4Atom.typeToInt("stsz"), 0);
                                        if (stsz != null) {
                                            log.debug("Sample size atom found");
                                            audioSamples = stsz.getSamples();
                                            //vector full of integers                              
                                            log.debug("Sample size: {}", stsz.getSampleSize());
                                            log.debug("Sample count: {}", audioSamples.size());
                                        }
                                        //stco - has Chunks
                                        MP4Atom stco = stbl.lookup(MP4Atom.typeToInt("stco"), 0);
                                        if (stco != null) {
                                            log.debug("Chunk offset atom found");
                                            //vector full of integers
                                            audioChunkOffsets = stco.getChunks();
                                            log.debug("Chunk count: {}", audioChunkOffsets.size());
                                        }
                                        //stts - has TimeSampleRecords
                                        MP4Atom stts = stbl.lookup(MP4Atom.typeToInt("stts"), 0);
                                        if (stts != null) {
                                            log.debug("Time to sample atom found");
                                            Vector<MP4Atom.TimeSampleRecord> records = stts
                                                    .getTimeToSamplesRecords();
                                            log.debug("Record count: {}", records.size());
                                            MP4Atom.TimeSampleRecord rec = records.firstElement();
                                            log.debug("Record data: Consecutive samples={} Duration={}",
                                                    rec.getConsecutiveSamples(), rec.getSampleDuration());
                                            //if we have 1 record then all samples have the same duration
                                            if (records.size() > 1) {
                                                //TODO: handle audio samples with varying durations
                                                log.info(
                                                        "Audio samples have differing durations, audio playback may fail");
                                            }
                                            audioSampleDuration = rec.getSampleDuration();
                                        }
                                    }
                                }
                                MP4Atom vmhd = minf.lookup(MP4Atom.typeToInt("vmhd"), 0);
                                if (vmhd != null) {
                                    log.debug("Video header atom found");
                                    MP4Atom dinf = minf.lookup(MP4Atom.typeToInt("dinf"), 0);
                                    if (dinf != null) {
                                        log.debug("Data info atom found");
                                        // dinf: dref
                                        log.debug("Video dinf children: {}", dinf.getChildren());
                                        MP4Atom dref = dinf.lookup(MP4Atom.typeToInt("dref"), 0);
                                        if (dref != null) {
                                            log.debug("Data reference atom found");
                                        }
                                    }
                                    MP4Atom stbl = minf.lookup(MP4Atom.typeToInt("stbl"), 0);
                                    if (stbl != null) {
                                        log.debug("Sample table atom found");
                                        // stbl: stsd, stts, stss, stsc, stsz, stco,
                                        // stsh
                                        log.debug("Video stbl children: {}", stbl.getChildren());
                                        // stsd - sample description
                                        // stts - (decoding) time to sample
                                        // stsc - sample to chunk
                                        // stsz - sample size
                                        // stco - chunk offset
                                        // ctts - (composition) time to sample
                                        // stss - sync sample
                                        // sdtp - independent and disposable samples

                                        //stsd - has codec child
                                        MP4Atom stsd = stbl.lookup(MP4Atom.typeToInt("stsd"), 0);
                                        if (stsd != null) {
                                            log.debug("Sample description atom found");
                                            log.debug("Sample description (video) stsd children: {}",
                                                    stsd.getChildren());
                                            MP4Atom avc1 = stsd.lookup(MP4Atom.typeToInt("avc1"), 0);
                                            if (avc1 != null) {
                                                log.debug("AVC1 children: {}", avc1.getChildren());
                                                //set the video codec here - may be avc1 or mp4v
                                                setVideoCodecId(MP4Atom.intToType(avc1.getType()));
                                                //video decoder config
                                                //TODO may need to be generic later
                                                MP4Atom codecChild = avc1.lookup(MP4Atom.typeToInt("avcC"), 0);
                                                if (codecChild != null) {
                                                    avcLevel = codecChild.getAvcLevel();
                                                    log.debug("AVC level: {}", avcLevel);
                                                    avcProfile = codecChild.getAvcProfile();
                                                    log.debug("AVC Profile: {}", avcProfile);
                                                    log.debug("AVCC size: {}", codecChild.getSize());
                                                    videoDecoderBytes = codecChild.getVideoConfigBytes();
                                                    log.debug("Video config bytes: {}", ToStringBuilder
                                                            .reflectionToString(videoDecoderBytes));
                                                } else {
                                                    //quicktime and ipods use a pixel aspect atom
                                                    //since we have no avcC check for this and avcC may
                                                    //be a child
                                                    MP4Atom pasp = avc1.lookup(MP4Atom.typeToInt("pasp"), 0);
                                                    if (pasp != null) {
                                                        log.debug("PASP children: {}", pasp.getChildren());
                                                        codecChild = pasp.lookup(MP4Atom.typeToInt("avcC"), 0);
                                                        if (codecChild != null) {
                                                            avcLevel = codecChild.getAvcLevel();
                                                            log.debug("AVC level: {}", avcLevel);
                                                            avcProfile = codecChild.getAvcProfile();
                                                            log.debug("AVC Profile: {}", avcProfile);
                                                            log.debug("AVCC size: {}", codecChild.getSize());
                                                            videoDecoderBytes = codecChild
                                                                    .getVideoConfigBytes();
                                                            log.debug("Video config bytes: {}", ToStringBuilder
                                                                    .reflectionToString(videoDecoderBytes));
                                                        }
                                                    }
                                                }
                                            } else {
                                                //look for mp4v
                                                MP4Atom mp4v = stsd.lookup(MP4Atom.typeToInt("mp4v"), 0);
                                                if (mp4v != null) {
                                                    log.debug("MP4V children: {}", mp4v.getChildren());
                                                    //set the video codec here - may be avc1 or mp4v
                                                    setVideoCodecId(MP4Atom.intToType(mp4v.getType()));
                                                    //look for esds 
                                                    MP4Atom codecChild = mp4v.lookup(MP4Atom.typeToInt("esds"),
                                                            0);
                                                    if (codecChild != null) {
                                                        //look for descriptors
                                                        MP4Descriptor descriptor = codecChild
                                                                .getEsd_descriptor();
                                                        log.debug("{}",
                                                                ToStringBuilder.reflectionToString(descriptor));
                                                        if (descriptor != null) {
                                                            Vector<MP4Descriptor> children = descriptor
                                                                    .getChildren();
                                                            for (int e = 0; e < children.size(); e++) {
                                                                MP4Descriptor descr = children.get(e);
                                                                log.debug("{}", ToStringBuilder
                                                                        .reflectionToString(descr));
                                                                if (descr.getChildren().size() > 0) {
                                                                    Vector<MP4Descriptor> children2 = descr
                                                                            .getChildren();
                                                                    for (int e2 = 0; e2 < children2
                                                                            .size(); e2++) {
                                                                        MP4Descriptor descr2 = children2
                                                                                .get(e2);
                                                                        log.debug("{}", ToStringBuilder
                                                                                .reflectionToString(descr2));
                                                                        if (descr2
                                                                                .getType() == MP4Descriptor.MP4DecSpecificInfoDescriptorTag) {
                                                                            //we only want the MP4DecSpecificInfoDescriptorTag                                        
                                                                            videoDecoderBytes = new byte[descr2
                                                                                    .getDSID().length - 8];
                                                                            System.arraycopy(descr2.getDSID(),
                                                                                    8, videoDecoderBytes, 0,
                                                                                    videoDecoderBytes.length);
                                                                            log.debug("Video config bytes: {}",
                                                                                    ToStringBuilder
                                                                                            .reflectionToString(
                                                                                                    videoDecoderBytes));
                                                                            //we want to break out of top level for loop
                                                                            e = 99;
                                                                            break;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                            log.debug("{}", ToStringBuilder.reflectionToString(avc1));
                                        }
                                        //stsc - has Records
                                        MP4Atom stsc = stbl.lookup(MP4Atom.typeToInt("stsc"), 0);
                                        if (stsc != null) {
                                            log.debug("Sample to chunk atom found");
                                            videoSamplesToChunks = stsc.getRecords();
                                            log.debug("Record count: {}", videoSamplesToChunks.size());
                                            MP4Atom.Record rec = videoSamplesToChunks.firstElement();
                                            log.debug("Record data: Description index={} Samples per chunk={}",
                                                    rec.getSampleDescriptionIndex(), rec.getSamplesPerChunk());
                                        }
                                        //stsz - has Samples
                                        MP4Atom stsz = stbl.lookup(MP4Atom.typeToInt("stsz"), 0);
                                        if (stsz != null) {
                                            log.debug("Sample size atom found");
                                            //vector full of integers                     
                                            videoSamples = stsz.getSamples();
                                            //if sample size is 0 then the table must be checked due
                                            //to variable sample sizes
                                            log.debug("Sample size: {}", stsz.getSampleSize());
                                            videoSampleCount = videoSamples.size();
                                            log.debug("Sample count: {}", videoSampleCount);
                                        }
                                        //stco - has Chunks
                                        MP4Atom stco = stbl.lookup(MP4Atom.typeToInt("stco"), 0);
                                        if (stco != null) {
                                            log.debug("Chunk offset atom found");
                                            //vector full of integers
                                            videoChunkOffsets = stco.getChunks();
                                            log.debug("Chunk count: {}", videoChunkOffsets.size());
                                        }
                                        //stss - has Sync - no sync means all samples are keyframes
                                        MP4Atom stss = stbl.lookup(MP4Atom.typeToInt("stss"), 0);
                                        if (stss != null) {
                                            log.debug("Sync sample atom found");
                                            //vector full of integers
                                            syncSamples = stss.getSyncSamples();
                                            log.debug("Keyframes: {}", syncSamples.size());
                                        }
                                        //stts - has TimeSampleRecords
                                        MP4Atom stts = stbl.lookup(MP4Atom.typeToInt("stts"), 0);
                                        if (stts != null) {
                                            log.debug("Time to sample atom found");
                                            Vector<MP4Atom.TimeSampleRecord> records = stts
                                                    .getTimeToSamplesRecords();
                                            log.debug("Record count: {}", records.size());
                                            MP4Atom.TimeSampleRecord rec = records.firstElement();
                                            log.debug("Record data: Consecutive samples={} Duration={}",
                                                    rec.getConsecutiveSamples(), rec.getSampleDuration());
                                            //if we have 1 record then all samples have the same duration
                                            if (records.size() > 1) {
                                                //TODO: handle video samples with varying durations
                                                log.info(
                                                        "Video samples have differing durations, video playback may fail");
                                            }
                                            videoSampleDuration = rec.getSampleDuration();
                                        }
                                        //ctts - (composition) time to sample
                                        MP4Atom ctts = stbl.lookup(MP4Atom.typeToInt("ctts"), 0);
                                        if (ctts != null) {
                                            log.debug("Composition time to sample atom found");
                                            //vector full of integers
                                            compositionTimes = ctts.getCompositionTimeToSamplesRecords();
                                            log.debug("Record count: {}", compositionTimes.size());
                                            if (log.isTraceEnabled()) {
                                                for (CompositionTimeSampleRecord rec : compositionTimes) {
                                                    double offset = rec.getSampleOffset();
                                                    if (scale > 0d) {
                                                        offset = (offset / (double) scale) * 1000.0;
                                                        rec.setSampleOffset((int) offset);
                                                    }
                                                    log.trace("Record data: Consecutive samples={} Offset={}",
                                                            rec.getConsecutiveSamples(), rec.getSampleOffset());
                                                }
                                            }
                                        }
                                    }
                                }

                            }

                        }
                    }
                    loops++;
                } while (loops < 3);
                log.trace("Busted out of track loop with {} tracks after {} loops", tracks, loops);
                //calculate FPS
                fps = (videoSampleCount * timeScale) / (double) duration;
                log.debug("FPS calc: ({} * {}) / {}", new Object[] { videoSampleCount, timeScale, duration });
                log.debug("FPS: {}", fps);

                //real duration
                StringBuilder sb = new StringBuilder();
                double videoTime = ((double) duration / (double) timeScale);
                log.debug("Video time: {}", videoTime);
                int minutes = (int) (videoTime / 60);
                if (minutes > 0) {
                    sb.append(minutes);
                    sb.append('.');
                }
                //formatter for seconds / millis
                NumberFormat df = DecimalFormat.getInstance();
                df.setMaximumFractionDigits(2);
                sb.append(df.format((videoTime % 60)));
                formattedDuration = sb.toString();
                log.debug("Time: {}", formattedDuration);

                break;
            case 1835295092: //mdat
                topAtoms++;
                long dataSize = 0L;
                MP4Atom mdat = atom;
                dataSize = mdat.getSize();
                log.debug("{}", ToStringBuilder.reflectionToString(mdat));
                mdatOffset = fis.getOffset() - dataSize;
                log.debug("File size: {} mdat size: {}", file.length(), dataSize);

                break;
            case 1718773093: //free
            case 2003395685: //wide
                break;
            default:
                log.warn("Unexpected atom: {}", MP4Atom.intToType(atom.getType()));
            }
        }

        //add the tag name (size) to the offsets
        moovOffset += 8;
        mdatOffset += 8;
        log.debug("Offsets moov: {} mdat: {}", moovOffset, mdatOffset);

    } catch (IOException e) {
        log.error("Exception decoding header / atoms", e);
    }
}

From source file:edu.snu.leader.discrete.simulator.SimulatorLauncherGUI.java

/**
 * Create the frame./* w w  w. j  ava2s .  c o m*/
 */
public SimulatorLauncherGUI() {
    NumberFormat countFormat = NumberFormat.getNumberInstance();
    countFormat.setParseIntegerOnly(true);

    NumberFormat doubleFormat = NumberFormat.getNumberInstance();
    doubleFormat.setMinimumIntegerDigits(1);
    doubleFormat.setMaximumFractionDigits(10);

    setTitle("Simulator");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 515, 340);
    setResizable(false);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    contentPane.add(tabbedPane, BorderLayout.CENTER);

    JPanel panelTab1 = new JPanel();
    tabbedPane.addTab("Simulator", null, panelTab1, null);

    JPanel panelAgentCount = new JPanel();
    panelTab1.add(panelAgentCount);

    JLabel lblNewLabel = new JLabel("Agent Count");
    panelAgentCount.add(lblNewLabel);

    sliderAgent = new JSlider();
    panelAgentCount.add(sliderAgent);
    sliderAgent.setValue(10);
    sliderAgent.setSnapToTicks(true);
    sliderAgent.setPaintTicks(true);
    sliderAgent.setPaintLabels(true);
    sliderAgent.setMinorTickSpacing(10);
    sliderAgent.setMajorTickSpacing(10);
    sliderAgent.setMinimum(10);
    sliderAgent.setMaximum(70);

    sliderAgent.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent arg0) {
            Integer spinnerValue = (Integer) spinnerMaxEaten.getValue();
            if (spinnerValue > sliderAgent.getValue()) {
                spinnerValue = sliderAgent.getValue();
            }
            spinnerMaxEaten.setModel(new SpinnerNumberModel(spinnerValue, new Integer(0),
                    new Integer(sliderAgent.getValue()), new Integer(1)));
            JFormattedTextField tfMaxEaten = ((JSpinner.DefaultEditor) spinnerMaxEaten.getEditor())
                    .getTextField();
            tfMaxEaten.setEditable(false);
        }
    });

    JPanel panelCommType = new JPanel();
    panelTab1.add(panelCommType);

    JLabel lblNewLabel_1 = new JLabel("Communication Type");
    panelCommType.add(lblNewLabel_1);

    comboBoxCommType = new JComboBox<String>();
    panelCommType.add(comboBoxCommType);
    comboBoxCommType
            .setModel(new DefaultComboBoxModel<String>(new String[] { "Global", "Topological", "Metric" }));
    comboBoxCommType.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            String item = (String) comboBoxCommType.getSelectedItem();
            if (item.equals("Topological")) {
                panelNearestNeighborCount.setVisible(true);
                panelMaxLocationRadius.setVisible(false);
            } else if (item.equals("Metric")) {
                panelNearestNeighborCount.setVisible(false);
                panelMaxLocationRadius.setVisible(true);
            } else if (item.equals("Global")) {
                panelNearestNeighborCount.setVisible(false);
                panelMaxLocationRadius.setVisible(false);
            }
        }
    });

    JPanel panelDestinationRadius = new JPanel();
    panelTab1.add(panelDestinationRadius);

    JLabel lblDestinationRadius = new JLabel("Destination Radius");
    panelDestinationRadius.add(lblDestinationRadius);

    frmtdtxtfldDestinationRadius = new JFormattedTextField(doubleFormat);
    frmtdtxtfldDestinationRadius.setColumns(4);
    frmtdtxtfldDestinationRadius.setValue((Number) 10);
    panelDestinationRadius.add(frmtdtxtfldDestinationRadius);

    JPanel panelResultsOutput = new JPanel();
    panelTab1.add(panelResultsOutput);

    JLabel lblResultsOutput = new JLabel("Results Output");
    panelResultsOutput.add(lblResultsOutput);

    final JCheckBox chckbxEskridge = new JCheckBox("Eskridge");
    panelResultsOutput.add(chckbxEskridge);

    final JCheckBox chckbxConflict = new JCheckBox("Conflict");
    panelResultsOutput.add(chckbxConflict);

    final JCheckBox chckbxPosition = new JCheckBox("Position");
    panelResultsOutput.add(chckbxPosition);

    final JCheckBox chckbxPredationResults = new JCheckBox("Predation");
    panelResultsOutput.add(chckbxPredationResults);

    JPanel panelMisc = new JPanel();
    panelTab1.add(panelMisc);

    JLabel lblNewLabel_3 = new JLabel("Misc");
    panelMisc.add(lblNewLabel_3);

    chckbxGraphical = new JCheckBox("Graphical?");
    chckbxGraphical.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (chckbxGraphical.isSelected()) {
                frmtdtxtfldRunCount.setValue((Number) 1);
                frmtdtxtfldRunCount.setEnabled(false);
                chckbxEskridge.setSelected(false);
                chckbxEskridge.setEnabled(false);
                String agentBuilder = (String) comboBoxAgentBuilder.getSelectedItem();
                if (agentBuilder.equals("Default")) {
                    comboBoxAgentBuilder.setSelectedIndex(1);
                }
            } else {
                chckbxEskridge.setEnabled(true);
                frmtdtxtfldRunCount.setEnabled(true);
            }
        }

    });
    panelMisc.add(chckbxGraphical);

    chckbxRandomSeed = new JCheckBox("Random Seed?");
    panelMisc.add(chckbxRandomSeed);

    chckbxPredationEnable = new JCheckBox("Predation?");
    chckbxPredationEnable.setSelected(true);
    chckbxPredationEnable.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (chckbxPredationEnable.isSelected()) {
                panelPredationStuff.setVisible(true);
                panelPredationBoxes.setVisible(true);
                panelPredationConstant.setVisible(true);
                panelNonMoversSurvive.setVisible(true);
            } else {
                panelPredationStuff.setVisible(false);
                panelPredationBoxes.setVisible(false);
                panelPredationConstant.setVisible(false);
                panelNonMoversSurvive.setVisible(false);
            }
        }
    });
    panelMisc.add(chckbxPredationEnable);

    JPanel panelCounts = new JPanel();
    panelTab1.add(panelCounts);

    JLabel lblNewLabel_4 = new JLabel("Run Count");
    panelCounts.add(lblNewLabel_4);

    frmtdtxtfldRunCount = new JFormattedTextField(countFormat);
    frmtdtxtfldRunCount.setToolTipText("The number of runs. Each run has a different random seed.");
    panelCounts.add(frmtdtxtfldRunCount);
    frmtdtxtfldRunCount.setColumns(4);
    frmtdtxtfldRunCount.setValue((Number) 1);

    JLabel lblNewLabel_5 = new JLabel("Sim Count");
    panelCounts.add(lblNewLabel_5);

    frmtdtxtfldSimCount = new JFormattedTextField(countFormat);
    frmtdtxtfldSimCount
            .setToolTipText("The number of simulations per run. Each simulation uses the same random seed.");
    frmtdtxtfldSimCount.setColumns(4);
    frmtdtxtfldSimCount.setValue((Number) 1);
    panelCounts.add(frmtdtxtfldSimCount);

    JLabel lblNewLabel_6 = new JLabel("Max Time Steps");
    panelCounts.add(lblNewLabel_6);

    frmtdtxtfldMaxTimeSteps = new JFormattedTextField(countFormat);
    frmtdtxtfldMaxTimeSteps.setToolTipText("The max number of time steps per simulation.");
    frmtdtxtfldMaxTimeSteps.setColumns(6);
    frmtdtxtfldMaxTimeSteps.setValue((Number) 20000);
    panelCounts.add(frmtdtxtfldMaxTimeSteps);

    ////////Panel tab 2

    JPanel panelTab2 = new JPanel();
    tabbedPane.addTab("Parameters", null, panelTab2, null);

    JPanel panelDecisionCalculator = new JPanel();
    panelTab2.add(panelDecisionCalculator);

    JLabel lblDecisionCalculator = new JLabel("Decision Calculator");
    panelDecisionCalculator.add(lblDecisionCalculator);

    final JComboBox<String> comboBoxDecisionCalculator = new JComboBox<String>();
    panelDecisionCalculator.add(comboBoxDecisionCalculator);
    comboBoxDecisionCalculator.setModel(
            new DefaultComboBoxModel<String>(new String[] { "Default", "Conflict", "Conflict Uninformed" }));

    JPanel panelAgentBuilder = new JPanel();
    panelTab2.add(panelAgentBuilder);

    JLabel lblAgentBuilder = new JLabel("Agent Builder");
    panelAgentBuilder.add(lblAgentBuilder);

    comboBoxAgentBuilder = new JComboBox<String>();
    panelAgentBuilder.add(comboBoxAgentBuilder);
    comboBoxAgentBuilder.setModel(new DefaultComboBoxModel<String>(new String[] { "Default", "Simple Angular",
            "Personality Simple Angular", "Simple Angular Uninformed" }));
    comboBoxAgentBuilder.setSelectedIndex(1);
    comboBoxAgentBuilder.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (chckbxGraphical.isSelected()) {
                String agentBuilder = (String) comboBoxAgentBuilder.getSelectedItem();
                if (agentBuilder.equals("Default")) {
                    comboBoxAgentBuilder.setSelectedIndex(1);
                }
            }
        }
    });

    JPanel panelModel = new JPanel();
    panelTab2.add(panelModel);

    JLabel lblModel = new JLabel("Model");
    panelModel.add(lblModel);

    comboBoxModel = new JComboBox<String>();
    panelModel.add(comboBoxModel);
    comboBoxModel.setModel(new DefaultComboBoxModel<String>(new String[] { "Sueur", "Gautrais" }));
    comboBoxModel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            String item = (String) comboBoxModel.getSelectedItem();
            if (item.equals("Sueur")) {
                panelSueurValues.setVisible(true);
                panelGautraisValues.setVisible(false);
            } else if (item.equals("Gautrais")) {
                panelSueurValues.setVisible(false);
                panelGautraisValues.setVisible(true);
            }
        }
    });

    JPanel panelEnvironment = new JPanel();
    panelTab2.add(panelEnvironment);

    JLabel lblEnvironment = new JLabel("Environment");
    panelEnvironment.add(lblEnvironment);

    comboBoxEnvironment = new JComboBox<String>();
    comboBoxEnvironment.setModel(
            new DefaultComboBoxModel<String>(new String[] { "Minimum", "Medium", "Maximum", "Uninformed" }));
    comboBoxEnvironment.setSelectedIndex(1);
    comboBoxEnvironment.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            String item = (String) comboBoxEnvironment.getSelectedItem();
            if (!item.equals("Uninformed")) {
                comboBoxDecisionCalculator.setEnabled(true);
                comboBoxAgentBuilder.setEnabled(true);
            }

            if (item.equals("Medium")) {
                panelAngle.setVisible(true);
                panelDistance.setVisible(true);
                panelPercentage.setVisible(true);
                panelNumberOfDestinations.setVisible(false);
                panelInformedCount.setVisible(false);
            } else if (item.equals("Minimum")) {
                panelAngle.setVisible(false);
                panelDistance.setVisible(false);
                panelPercentage.setVisible(true);
                panelNumberOfDestinations.setVisible(false);
                panelInformedCount.setVisible(false);
            } else if (item.equals("Maximum")) {
                panelAngle.setVisible(false);
                panelDistance.setVisible(false);
                panelPercentage.setVisible(true);
                panelNumberOfDestinations.setVisible(false);
                panelInformedCount.setVisible(false);
            } else if (item.equals("Uninformed")) {
                panelAngle.setVisible(true);
                panelDistance.setVisible(true);
                panelPercentage.setVisible(true);
                panelNumberOfDestinations.setVisible(false);
                panelInformedCount.setVisible(true);
                comboBoxDecisionCalculator.setSelectedIndex(2);
                comboBoxDecisionCalculator.setEnabled(false);
                comboBoxAgentBuilder.setSelectedIndex(3);
                comboBoxAgentBuilder.setEnabled(false);
            }
        }
    });
    panelEnvironment.add(comboBoxEnvironment);

    JPanel panelDefaultConflict = new JPanel();
    panelTab2.add(panelDefaultConflict);

    JLabel lblDefaultConflict = new JLabel("Default Conflict");
    panelDefaultConflict.add(lblDefaultConflict);

    final JSpinner spinnerDefaultConflict = new JSpinner();
    panelDefaultConflict.add(spinnerDefaultConflict);
    spinnerDefaultConflict.setModel(
            new SpinnerNumberModel(new Float(0.9f), new Float(0.1f), new Float(0.91f), new Float(0.05)));
    JFormattedTextField tfSpinnerConflict = ((JSpinner.DefaultEditor) spinnerDefaultConflict.getEditor())
            .getTextField();
    tfSpinnerConflict.setEditable(false);

    JPanel panelCancelationThreshold = new JPanel();
    panelTab2.add(panelCancelationThreshold);

    JLabel lblCancelationThreshold = new JLabel("Cancelation Threshold");
    panelCancelationThreshold.add(lblCancelationThreshold);

    final JSpinner spinnerCancelationThreshold = new JSpinner();
    panelCancelationThreshold.add(spinnerCancelationThreshold);
    spinnerCancelationThreshold.setModel(
            new SpinnerNumberModel(new Float(1.0f), new Float(0.0f), new Float(1.01f), new Float(0.05)));
    JFormattedTextField tfCancelationThreshold = ((JSpinner.DefaultEditor) spinnerCancelationThreshold
            .getEditor()).getTextField();
    tfCancelationThreshold.setEditable(false);

    JPanel panelStopAnywhere = new JPanel();
    panelTab2.add(panelStopAnywhere);

    final JCheckBox chckbxStopAnywhere = new JCheckBox("Stop Anywhere?");
    panelStopAnywhere.add(chckbxStopAnywhere);

    panelNearestNeighborCount = new JPanel();
    panelNearestNeighborCount.setVisible(false);
    panelTab2.add(panelNearestNeighborCount);

    JLabel lblNearestNeighborCount = new JLabel("Nearest Neighbor Count");
    panelNearestNeighborCount.add(lblNearestNeighborCount);

    frmtdtxtfldNearestNeighborCount = new JFormattedTextField(countFormat);
    panelNearestNeighborCount.add(frmtdtxtfldNearestNeighborCount);
    frmtdtxtfldNearestNeighborCount.setColumns(3);
    frmtdtxtfldNearestNeighborCount.setValue((Number) 10);

    panelMaxLocationRadius = new JPanel();
    panelMaxLocationRadius.setVisible(false);
    panelTab2.add(panelMaxLocationRadius);

    JLabel lblMaxLocationRadius = new JLabel("Max Location Radius");
    panelMaxLocationRadius.add(lblMaxLocationRadius);

    frmtdtxtfldMaxLocationRadius = new JFormattedTextField(doubleFormat);
    panelMaxLocationRadius.add(frmtdtxtfldMaxLocationRadius);
    frmtdtxtfldMaxLocationRadius.setColumns(5);
    frmtdtxtfldMaxLocationRadius.setValue((Number) 10.0);

    panelPredationBoxes = new JPanel();
    panelTab2.add(panelPredationBoxes);

    final JCheckBox chckbxUsePredationThreshold = new JCheckBox("Use Predation Threshold");
    panelPredationBoxes.add(chckbxUsePredationThreshold);

    final JCheckBox chckbxPopulationIndependent = new JCheckBox("Population Independent");
    chckbxPopulationIndependent.setSelected(true);
    panelPredationBoxes.add(chckbxPopulationIndependent);
    chckbxPopulationIndependent.setToolTipText(
            "Select this to allow predation to be independent of population size. Max predation for 10 agents will be the same as for 50 agents. ");

    panelPredationStuff = new JPanel();
    panelTab2.add(panelPredationStuff);

    JLabel lblPredationMinimum = new JLabel("Predation Minimum");
    panelPredationStuff.add(lblPredationMinimum);

    frmtdtxtfldPredationMinimum = new JFormattedTextField(doubleFormat);
    frmtdtxtfldPredationMinimum.setColumns(4);
    frmtdtxtfldPredationMinimum.setValue((Number) 0.0);
    panelPredationStuff.add(frmtdtxtfldPredationMinimum);

    JLabel lblPredationThreshold = new JLabel("Predation Threshold");
    panelPredationStuff.add(lblPredationThreshold);

    final JSpinner spinnerPredationThreshold = new JSpinner();
    panelPredationStuff.add(spinnerPredationThreshold);
    spinnerPredationThreshold.setModel(
            new SpinnerNumberModel(new Float(1.0f), new Float(0.0f), new Float(1.01f), new Float(0.05)));
    JFormattedTextField tfPredationThreshold = ((JSpinner.DefaultEditor) spinnerPredationThreshold.getEditor())
            .getTextField();
    tfPredationThreshold.setEditable(false);

    JLabel lblMaxEaten = new JLabel("Max Eaten");
    panelPredationStuff.add(lblMaxEaten);

    spinnerMaxEaten = new JSpinner();
    spinnerMaxEaten.setToolTipText("The max number eaten per time step.");
    panelPredationStuff.add(spinnerMaxEaten);
    spinnerMaxEaten.setModel(new SpinnerNumberModel(new Integer(10), new Integer(0),
            new Integer(sliderAgent.getValue()), new Integer(1)));
    JFormattedTextField tfMaxEaten = ((JSpinner.DefaultEditor) spinnerMaxEaten.getEditor()).getTextField();
    tfMaxEaten.setEditable(false);

    panelPredationConstant = new JPanel();
    panelTab2.add(panelPredationConstant);

    JLabel lblPredationConstant = new JLabel("Predation Constant");
    panelPredationConstant.add(lblPredationConstant);

    frmtdtxtfldPredationConstant = new JFormattedTextField(doubleFormat);
    panelPredationConstant.add(frmtdtxtfldPredationConstant);
    frmtdtxtfldPredationConstant.setToolTipText("Value should be positive. Recommended values are near 0.001");
    frmtdtxtfldPredationConstant.setColumns(4);
    frmtdtxtfldPredationConstant.setValue((Number) 0.001);

    panelNonMoversSurvive = new JPanel();
    panelTab2.add(panelNonMoversSurvive);

    final JCheckBox chckbxNonMoversSurvive = new JCheckBox("Non-movers Survive?");
    chckbxNonMoversSurvive.setSelected(false);
    panelNonMoversSurvive.add(chckbxNonMoversSurvive);

    ////////Tab 3

    JPanel panelTab3 = new JPanel();
    tabbedPane.addTab("Environment", null, panelTab3, null);
    panelTab3.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

    panelSueurValues = new JPanel();
    panelTab3.add(panelSueurValues);
    panelSueurValues.setLayout(new BoxLayout(panelSueurValues, BoxLayout.Y_AXIS));

    JLabel lblSueurValues = new JLabel("Sueur Values");
    lblSueurValues.setHorizontalAlignment(SwingConstants.TRAILING);
    lblSueurValues.setAlignmentX(Component.CENTER_ALIGNMENT);
    panelSueurValues.add(lblSueurValues);

    JPanel panelAlpha = new JPanel();
    FlowLayout flowLayout = (FlowLayout) panelAlpha.getLayout();
    flowLayout.setAlignment(FlowLayout.RIGHT);
    panelSueurValues.add(panelAlpha);

    JLabel lblAlpha = new JLabel("alpha");
    lblAlpha.setHorizontalAlignment(SwingConstants.CENTER);
    panelAlpha.add(lblAlpha);

    final JFormattedTextField frmtdtxtfldAlpha = new JFormattedTextField(doubleFormat);
    frmtdtxtfldAlpha.setHorizontalAlignment(SwingConstants.TRAILING);
    lblAlpha.setLabelFor(frmtdtxtfldAlpha);
    panelAlpha.add(frmtdtxtfldAlpha);
    frmtdtxtfldAlpha.setColumns(6);
    frmtdtxtfldAlpha.setValue((Number) 0.006161429);

    JPanel panelAlphaC = new JPanel();
    FlowLayout flowLayout_2 = (FlowLayout) panelAlphaC.getLayout();
    flowLayout_2.setAlignment(FlowLayout.RIGHT);
    panelSueurValues.add(panelAlphaC);

    JLabel lblAlphaC = new JLabel("alpha c");
    panelAlphaC.add(lblAlphaC);

    final JFormattedTextField frmtdtxtfldAlphaC = new JFormattedTextField(doubleFormat);
    frmtdtxtfldAlphaC.setHorizontalAlignment(SwingConstants.TRAILING);
    lblAlphaC.setLabelFor(frmtdtxtfldAlphaC);
    panelAlphaC.add(frmtdtxtfldAlphaC);
    frmtdtxtfldAlphaC.setColumns(6);
    frmtdtxtfldAlphaC.setValue((Number) 0.009);

    JPanel panelBeta = new JPanel();
    FlowLayout flowLayout_1 = (FlowLayout) panelBeta.getLayout();
    flowLayout_1.setAlignment(FlowLayout.RIGHT);
    panelSueurValues.add(panelBeta);

    JLabel lblBeta = new JLabel("beta");
    panelBeta.add(lblBeta);

    final JFormattedTextField frmtdtxtfldBeta = new JFormattedTextField(doubleFormat);
    frmtdtxtfldBeta.setHorizontalAlignment(SwingConstants.TRAILING);
    panelBeta.add(frmtdtxtfldBeta);
    frmtdtxtfldBeta.setColumns(6);
    frmtdtxtfldBeta.setValue((Number) 0.013422819);

    JPanel panelBetaC = new JPanel();
    FlowLayout flowLayout_14 = (FlowLayout) panelBetaC.getLayout();
    flowLayout_14.setAlignment(FlowLayout.RIGHT);
    panelSueurValues.add(panelBetaC);

    JLabel lblBetaC = new JLabel("beta c");
    panelBetaC.add(lblBetaC);

    final JFormattedTextField frmtdtxtfldBetaC = new JFormattedTextField(doubleFormat);
    frmtdtxtfldBetaC.setHorizontalAlignment(SwingConstants.TRAILING);
    panelBetaC.add(frmtdtxtfldBetaC);
    frmtdtxtfldBetaC.setColumns(6);
    frmtdtxtfldBetaC.setValue((Number) (-0.009));

    JPanel panelS = new JPanel();
    FlowLayout flowLayout_3 = (FlowLayout) panelS.getLayout();
    flowLayout_3.setAlignment(FlowLayout.RIGHT);
    panelSueurValues.add(panelS);

    JLabel lblS = new JLabel("S");
    panelS.add(lblS);

    final JFormattedTextField frmtdtxtfldS = new JFormattedTextField(countFormat);
    frmtdtxtfldS.setHorizontalAlignment(SwingConstants.TRAILING);
    panelS.add(frmtdtxtfldS);
    frmtdtxtfldS.setColumns(6);
    frmtdtxtfldS.setValue((Number) 2);

    JPanel panelQ = new JPanel();
    FlowLayout flowLayout_4 = (FlowLayout) panelQ.getLayout();
    flowLayout_4.setAlignment(FlowLayout.RIGHT);
    panelSueurValues.add(panelQ);

    JLabel lblQ = new JLabel("q");
    panelQ.add(lblQ);

    final JFormattedTextField frmtdtxtfldQ = new JFormattedTextField(doubleFormat);
    frmtdtxtfldQ.setHorizontalAlignment(SwingConstants.TRAILING);
    panelQ.add(frmtdtxtfldQ);
    frmtdtxtfldQ.setColumns(6);
    frmtdtxtfldQ.setValue((Number) 2.3);

    panelGautraisValues = new JPanel();
    panelGautraisValues.setVisible(false);
    panelTab3.add(panelGautraisValues);
    panelGautraisValues.setLayout(new BoxLayout(panelGautraisValues, BoxLayout.Y_AXIS));

    JLabel label = new JLabel("Gautrais Values");
    label.setAlignmentX(Component.CENTER_ALIGNMENT);
    panelGautraisValues.add(label);

    JPanel panelTauO = new JPanel();
    FlowLayout flowLayout_5 = (FlowLayout) panelTauO.getLayout();
    flowLayout_5.setAlignment(FlowLayout.RIGHT);
    panelGautraisValues.add(panelTauO);

    JLabel lblTauO = new JLabel("tau o");
    panelTauO.add(lblTauO);

    final JFormattedTextField frmtdtxtfldTaoO = new JFormattedTextField(doubleFormat);
    frmtdtxtfldTaoO.setHorizontalAlignment(SwingConstants.TRAILING);
    panelTauO.add(frmtdtxtfldTaoO);
    frmtdtxtfldTaoO.setColumns(4);
    frmtdtxtfldTaoO.setValue((Number) 1290);

    JPanel panelGammaC = new JPanel();
    FlowLayout flowLayout_6 = (FlowLayout) panelGammaC.getLayout();
    flowLayout_6.setAlignment(FlowLayout.RIGHT);
    panelGautraisValues.add(panelGammaC);

    JLabel lblGammaC = new JLabel("gamma c");
    panelGammaC.add(lblGammaC);

    final JFormattedTextField frmtdtxtfldGammaC = new JFormattedTextField(doubleFormat);
    frmtdtxtfldGammaC.setHorizontalAlignment(SwingConstants.TRAILING);
    panelGammaC.add(frmtdtxtfldGammaC);
    frmtdtxtfldGammaC.setColumns(4);
    frmtdtxtfldGammaC.setValue((Number) 2.0);

    JPanel panelEpsilonC = new JPanel();
    FlowLayout flowLayout_7 = (FlowLayout) panelEpsilonC.getLayout();
    flowLayout_7.setAlignment(FlowLayout.RIGHT);
    panelGautraisValues.add(panelEpsilonC);

    JLabel lblEpsilonC = new JLabel("epsilon c");
    panelEpsilonC.add(lblEpsilonC);

    final JFormattedTextField frmtdtxtfldEpsilonC = new JFormattedTextField(doubleFormat);
    frmtdtxtfldEpsilonC.setHorizontalAlignment(SwingConstants.TRAILING);
    panelEpsilonC.add(frmtdtxtfldEpsilonC);
    frmtdtxtfldEpsilonC.setColumns(4);
    frmtdtxtfldEpsilonC.setValue((Number) 2.3);

    JPanel panelAlphaF = new JPanel();
    FlowLayout flowLayout_8 = (FlowLayout) panelAlphaF.getLayout();
    flowLayout_8.setAlignment(FlowLayout.RIGHT);
    panelGautraisValues.add(panelAlphaF);

    JLabel lblAlphaF = new JLabel("alpha f");
    panelAlphaF.add(lblAlphaF);

    final JFormattedTextField frmtdtxtfldAlphaF = new JFormattedTextField(doubleFormat);
    frmtdtxtfldAlphaF.setHorizontalAlignment(SwingConstants.TRAILING);
    panelAlphaF.add(frmtdtxtfldAlphaF);
    frmtdtxtfldAlphaF.setColumns(4);
    frmtdtxtfldAlphaF.setValue((Number) 162.3);

    JPanel panelBetaF = new JPanel();
    FlowLayout flowLayout_9 = (FlowLayout) panelBetaF.getLayout();
    flowLayout_9.setAlignment(FlowLayout.RIGHT);
    panelGautraisValues.add(panelBetaF);

    JLabel lblBetaF = new JLabel("beta f");
    panelBetaF.add(lblBetaF);

    final JFormattedTextField frmtdtxtfldBetaF = new JFormattedTextField(doubleFormat);
    frmtdtxtfldBetaF.setHorizontalAlignment(SwingConstants.TRAILING);
    panelBetaF.add(frmtdtxtfldBetaF);
    frmtdtxtfldBetaF.setColumns(4);
    frmtdtxtfldBetaF.setValue((Number) 75.4);

    JPanel panelEnvironmentVariables = new JPanel();
    panelTab3.add(panelEnvironmentVariables);
    panelEnvironmentVariables.setLayout(new BoxLayout(panelEnvironmentVariables, BoxLayout.Y_AXIS));

    JLabel lblEnvironmentVariables = new JLabel("Environment Variables");
    lblEnvironmentVariables.setAlignmentX(Component.CENTER_ALIGNMENT);
    panelEnvironmentVariables.add(lblEnvironmentVariables);

    panelAngle = new JPanel();
    FlowLayout flowLayout_10 = (FlowLayout) panelAngle.getLayout();
    flowLayout_10.setAlignment(FlowLayout.RIGHT);
    panelEnvironmentVariables.add(panelAngle);

    JLabel lblAngle = new JLabel("Angle");
    panelAngle.add(lblAngle);

    final JFormattedTextField frmtdtxtfldAngle = new JFormattedTextField(doubleFormat);
    frmtdtxtfldAngle.setHorizontalAlignment(SwingConstants.TRAILING);
    frmtdtxtfldAngle.setToolTipText("Angle between destinations");
    panelAngle.add(frmtdtxtfldAngle);
    frmtdtxtfldAngle.setColumns(3);
    frmtdtxtfldAngle.setValue((Number) 72.00);

    panelNumberOfDestinations = new JPanel();
    FlowLayout flowLayout_13 = (FlowLayout) panelNumberOfDestinations.getLayout();
    flowLayout_13.setAlignment(FlowLayout.RIGHT);
    panelNumberOfDestinations.setVisible(false);
    panelEnvironmentVariables.add(panelNumberOfDestinations);

    JLabel lblNumberOfDestinations = new JLabel("Number of Destinations");
    panelNumberOfDestinations.add(lblNumberOfDestinations);

    JFormattedTextField frmtdtxtfldNumberOfDestinations = new JFormattedTextField(countFormat);
    frmtdtxtfldNumberOfDestinations.setHorizontalAlignment(SwingConstants.TRAILING);
    panelNumberOfDestinations.add(frmtdtxtfldNumberOfDestinations);
    frmtdtxtfldNumberOfDestinations.setColumns(3);
    frmtdtxtfldNumberOfDestinations.setValue((Number) 2);

    panelDistance = new JPanel();
    FlowLayout flowLayout_11 = (FlowLayout) panelDistance.getLayout();
    flowLayout_11.setAlignment(FlowLayout.RIGHT);
    panelEnvironmentVariables.add(panelDistance);

    JLabel lblDistance = new JLabel("Distance");
    panelDistance.add(lblDistance);

    frmtdtxtfldDistance = new JFormattedTextField(doubleFormat);
    frmtdtxtfldDistance.setHorizontalAlignment(SwingConstants.TRAILING);
    frmtdtxtfldDistance.setToolTipText("Distance the destination is from origin (0,0)");
    panelDistance.add(frmtdtxtfldDistance);
    frmtdtxtfldDistance.setColumns(3);
    frmtdtxtfldDistance.setValue((Number) 150.0);

    panelPercentage = new JPanel();
    FlowLayout flowLayout_12 = (FlowLayout) panelPercentage.getLayout();
    flowLayout_12.setAlignment(FlowLayout.RIGHT);
    panelEnvironmentVariables.add(panelPercentage);

    JLabel lblPercentage = new JLabel("Percentage");
    panelPercentage.add(lblPercentage);

    frmtdtxtfldPercentage = new JFormattedTextField(doubleFormat);
    frmtdtxtfldPercentage.setHorizontalAlignment(SwingConstants.TRAILING);
    frmtdtxtfldPercentage.setToolTipText(
            "The percentage moving to one of the two destinations ( The other gets 1 - percentage).");
    panelPercentage.add(frmtdtxtfldPercentage);
    frmtdtxtfldPercentage.setColumns(3);
    frmtdtxtfldPercentage.setValue((Number) 0.500);

    panelInformedCount = new JPanel();
    panelEnvironmentVariables.add(panelInformedCount);

    JLabel lblInformedCount = new JLabel("Informed Count");
    panelInformedCount.add(lblInformedCount);

    final JFormattedTextField frmtdtxtfldInformedCount = new JFormattedTextField(countFormat);
    frmtdtxtfldInformedCount.setHorizontalAlignment(SwingConstants.TRAILING);
    frmtdtxtfldInformedCount.setColumns(3);
    frmtdtxtfldInformedCount.setToolTipText(
            "The number of agents moving toward a preferred destination. This number is duplicated on the southern pole as well.");
    frmtdtxtfldInformedCount.setValue((Number) 4);
    panelInformedCount.setVisible(false);

    panelInformedCount.add(frmtdtxtfldInformedCount);

    JPanel panelStartButtons = new JPanel();

    JButton btnStartSimulation = new JButton("Create Simulator Instance");
    btnStartSimulation.setToolTipText("Creates a new simulator instance from the settings provided.");
    btnStartSimulation.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean isReady = true;
            ErrorPacketContainer errorPacketContainer = new ErrorPacketContainer();

            if (jframeErrorMessages != null && jframeErrorMessages.isVisible()) {
                jframeErrorMessages.dispose();
            }

            frmtdtxtfldRunCount.setBackground(Color.WHITE);
            frmtdtxtfldSimCount.setBackground(Color.WHITE);
            frmtdtxtfldMaxTimeSteps.setBackground(Color.WHITE);
            frmtdtxtfldPredationMinimum.setBackground(Color.WHITE);
            frmtdtxtfldPredationConstant.setBackground(Color.WHITE);
            frmtdtxtfldNearestNeighborCount.setBackground(Color.WHITE);
            frmtdtxtfldMaxLocationRadius.setBackground(Color.WHITE);
            frmtdtxtfldPercentage.setBackground(Color.WHITE);
            frmtdtxtfldDistance.setBackground(Color.WHITE);
            frmtdtxtfldDestinationRadius.setBackground(Color.WHITE);
            frmtdtxtfldAngle.setBackground(Color.WHITE);
            frmtdtxtfldInformedCount.setBackground(Color.WHITE);

            StringBuilder errorMessages = new StringBuilder();

            if (((Number) frmtdtxtfldRunCount.getValue()).intValue() <= 0) {
                errorMessages.append("Run Count must be positive\n");
                frmtdtxtfldRunCount.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Run Count must be positive", frmtdtxtfldRunCount, 0);
                isReady = false;
            }
            if (((Number) frmtdtxtfldSimCount.getValue()).intValue() <= 0) {
                errorMessages.append("Sim Count must be positive\n");
                frmtdtxtfldSimCount.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Sim Count must be positive", frmtdtxtfldSimCount, 0);
                isReady = false;
            }
            if (((Number) frmtdtxtfldMaxTimeSteps.getValue()).intValue() <= 0) {
                errorMessages.append("Max Time Steps must be positive\n");
                frmtdtxtfldMaxTimeSteps.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Max Time Steps must be positive", frmtdtxtfldMaxTimeSteps, 0);
                isReady = false;
            }
            if (((Number) frmtdtxtfldPredationMinimum.getValue()).doubleValue() < 0
                    && chckbxPredationEnable.isSelected()) {
                errorMessages.append("Predation Minimum must be positive\n");
                frmtdtxtfldPredationMinimum.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Predation Minimum must be positive",
                        frmtdtxtfldPredationMinimum, 1);
                isReady = false;
            }
            if (((Number) frmtdtxtfldPredationConstant.getValue()).doubleValue() <= 0
                    && chckbxPredationEnable.isSelected()) {
                errorMessages.append("Predation Constant must be positive\n");
                frmtdtxtfldPredationConstant.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Predation Constant must be positive",
                        frmtdtxtfldPredationConstant, 1);
                isReady = false;
            }
            if (((Number) frmtdtxtfldNearestNeighborCount.getValue()).intValue() < 0
                    && panelNearestNeighborCount.isVisible()) {
                errorMessages.append("Nearest Neighbor Count must be positive\n");
                frmtdtxtfldNearestNeighborCount.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Nearest Neighbor Count must be positive",
                        frmtdtxtfldNearestNeighborCount, 1);
                isReady = false;
            }
            if (((Number) frmtdtxtfldMaxLocationRadius.getValue()).doubleValue() < 0
                    && panelMaxLocationRadius.isVisible()) {
                errorMessages.append("Max Location Radius must be positive\n");
                frmtdtxtfldMaxLocationRadius.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Max Location Radius must be positive",
                        frmtdtxtfldMaxLocationRadius, 1);
                isReady = false;
            }
            if ((((Number) frmtdtxtfldPercentage.getValue()).doubleValue() < 0.0
                    || ((Number) frmtdtxtfldPercentage.getValue()).doubleValue() > 1.0)
                    && panelPercentage.isVisible()) {
                errorMessages.append(
                        "Percentage needs to be greater than or equal to 0 and less than or equal to 1\n");
                frmtdtxtfldPercentage.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket(
                        "Percentage needs to be greater than or equal to 0 and less than or equal to 1",
                        frmtdtxtfldPercentage, 2);
                isReady = false;
            }
            if (((Number) frmtdtxtfldDistance.getValue()).doubleValue() <= 0
                    && frmtdtxtfldDistance.isVisible()) {
                errorMessages.append("Distance must be positive\n");
                frmtdtxtfldDistance.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Distance must be positive", frmtdtxtfldDistance, 2);
                isReady = false;
            }
            if (((Number) frmtdtxtfldDestinationRadius.getValue()).doubleValue() <= 0) {
                errorMessages.append("Destination Radius must be positive\n");
                frmtdtxtfldDestinationRadius.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Destination Radius must be positive",
                        frmtdtxtfldDestinationRadius, 0);
                isReady = false;
            }
            if (((Number) frmtdtxtfldAngle.getValue()).doubleValue() < 0) {
                errorMessages.append("Angle must be positive or zero\n");
                frmtdtxtfldAngle.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Angle must be positive", frmtdtxtfldAngle, 2);
                isReady = false;
            }
            if (((Number) frmtdtxtfldInformedCount.getValue()).intValue() <= 0) {
                errorMessages.append("Informed Count must be positive\n");
                frmtdtxtfldInformedCount.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket("Informed Count must be positive", frmtdtxtfldInformedCount, 2);
                isReady = false;
            } else if (((Number) frmtdtxtfldInformedCount.getValue()).intValue() * 2 > sliderAgent.getValue()) {
                errorMessages.append("Informed Count should at most be half the count of total agents\n");
                frmtdtxtfldInformedCount.setBackground(Color.YELLOW);
                errorPacketContainer.addPacket(
                        "Informed Count should at most be half the count of total agents",
                        frmtdtxtfldInformedCount, 2);
                isReady = false;
            }

            if (!isReady) {
                jframeErrorMessages = createJFrameErrorMessages(errorPacketContainer, tabbedPane);
                jframeErrorMessages.setVisible(true);
            } else {
                _simulatorProperties = new Properties();

                _simulatorProperties.put("run-count", String.valueOf(frmtdtxtfldRunCount.getValue()));
                _simulatorProperties.put("simulation-count", String.valueOf(frmtdtxtfldSimCount.getValue()));
                _simulatorProperties.put("max-simulation-time-steps",
                        String.valueOf(frmtdtxtfldMaxTimeSteps.getValue()));
                _simulatorProperties.put("random-seed", String.valueOf(1)); // Doesn't change
                _simulatorProperties.put("individual-count", String.valueOf(sliderAgent.getValue()));
                _simulatorProperties.put("run-graphical", String.valueOf(chckbxGraphical.isSelected()));
                _simulatorProperties.put("pre-calculate-probabilities", String.valueOf(false)); // Doesn't change
                _simulatorProperties.put("use-random-random-seed",
                        String.valueOf(chckbxRandomSeed.isSelected()));
                _simulatorProperties.put("can-multiple-initiate", String.valueOf(true)); // Doesn't change

                _simulatorProperties.put("eskridge-results", String.valueOf(chckbxEskridge.isSelected()));
                _simulatorProperties.put("conflict-results", String.valueOf(chckbxConflict.isSelected()));
                _simulatorProperties.put("position-results", String.valueOf(chckbxPosition.isSelected()));
                _simulatorProperties.put("predation-results",
                        String.valueOf(chckbxPredationResults.isSelected()));

                _simulatorProperties.put("communication-type",
                        String.valueOf(comboBoxCommType.getSelectedItem()).toLowerCase());

                _simulatorProperties.put("nearest-neighbor-count",
                        String.valueOf(frmtdtxtfldNearestNeighborCount.getValue()));
                _simulatorProperties.put("max-location-radius",
                        String.valueOf(frmtdtxtfldMaxLocationRadius.getValue()));

                _simulatorProperties.put("destination-size-radius",
                        String.valueOf(frmtdtxtfldDestinationRadius.getValue()));

                _simulatorProperties.put("max-agents-eaten-per-step",
                        String.valueOf(spinnerMaxEaten.getValue()));
                _simulatorProperties.put("enable-predator", String.valueOf(chckbxPredationEnable.isSelected()));
                _simulatorProperties.put("predation-probability-minimum",
                        String.valueOf(frmtdtxtfldPredationMinimum.getValue()));
                _simulatorProperties.put("predation-multiplier",
                        String.valueOf(frmtdtxtfldPredationConstant.getValue()));
                _simulatorProperties.put("use-predation-threshold",
                        String.valueOf(chckbxUsePredationThreshold.isSelected()));
                _simulatorProperties.put("predation-threshold",
                        String.valueOf(spinnerPredationThreshold.getValue()));
                _simulatorProperties.put("predation-by-population",
                        String.valueOf(chckbxPopulationIndependent.isSelected()));
                _simulatorProperties.put("count-non-movers-as-survivors",
                        String.valueOf(chckbxNonMoversSurvive.isSelected()));

                _simulatorProperties.put("stop-at-any-destination",
                        String.valueOf(chckbxStopAnywhere.isSelected()));

                _simulatorProperties.put("adhesion-time-limit",
                        String.valueOf(frmtdtxtfldMaxTimeSteps.getValue()));

                _simulatorProperties.put("alpha", String.valueOf(frmtdtxtfldAlpha.getValue()));
                _simulatorProperties.put("alpha-c", String.valueOf(frmtdtxtfldAlphaC.getValue()));
                _simulatorProperties.put("beta", String.valueOf(frmtdtxtfldBeta.getValue()));
                _simulatorProperties.put("beta-c", String.valueOf(frmtdtxtfldBetaC.getValue()));
                _simulatorProperties.put("S", String.valueOf(frmtdtxtfldS.getValue()));
                _simulatorProperties.put("q", String.valueOf(frmtdtxtfldQ.getValue()));

                _simulatorProperties.put("lambda", String.valueOf(0.2));

                _simulatorProperties.put("tau-o", String.valueOf(frmtdtxtfldTaoO.getValue()));
                _simulatorProperties.put("gamma-c", String.valueOf(frmtdtxtfldGammaC.getValue()));
                _simulatorProperties.put("epsilon-c", String.valueOf(frmtdtxtfldEpsilonC.getValue()));
                _simulatorProperties.put("alpha-f", String.valueOf(frmtdtxtfldAlphaF.getValue()));
                _simulatorProperties.put("beta-f", String.valueOf(frmtdtxtfldBetaF.getValue()));

                _simulatorProperties.put("default-conflict-value",
                        String.valueOf(spinnerDefaultConflict.getValue()));

                _simulatorProperties.put("cancellation-threshold",
                        String.valueOf(spinnerCancelationThreshold.getValue()));
                StringBuilder sbAgentBuilder = new StringBuilder();
                sbAgentBuilder.append("edu.snu.leader.discrete.simulator.Sueur");
                sbAgentBuilder.append(comboBoxAgentBuilder.getSelectedItem().toString().replace(" ", ""));
                sbAgentBuilder.append("AgentBuilder");
                _simulatorProperties.put("agent-builder", String.valueOf(sbAgentBuilder.toString()));

                StringBuilder sbDecisionCalculator = new StringBuilder();
                sbDecisionCalculator.append("edu.snu.leader.discrete.simulator.");
                sbDecisionCalculator.append(comboBoxModel.getSelectedItem());
                //                    sbDecisionCalculator.append(comboBoxDecisionCalculator.getSelectedItem());
                sbDecisionCalculator
                        .append(comboBoxDecisionCalculator.getSelectedItem().toString().replace(" ", ""));
                sbDecisionCalculator.append("DecisionCalculator");
                _simulatorProperties.put("decision-calculator",
                        String.valueOf(sbDecisionCalculator.toString()));

                StringBuilder sbLocationsFile = new StringBuilder();
                sbLocationsFile.append("cfg/sim/locations/metric/valid-metric-loc-");
                sbLocationsFile.append(String.format("%03d", sliderAgent.getValue()));
                sbLocationsFile.append("-seed-00001.dat");
                _simulatorProperties.put("locations-file", String.valueOf(sbLocationsFile.toString()));

                //create destination file
                DestinationBuilder db = new DestinationBuilder(sliderAgent.getValue(), 1L);

                StringBuilder sbDestinationsFile = new StringBuilder();
                sbDestinationsFile.append("cfg/sim/destinations/destinations-");
                switch (comboBoxEnvironment.getSelectedItem().toString()) {
                case ("Minimum"):
                    sbDestinationsFile.append("diffdis-" + sliderAgent.getValue());
                    sbDestinationsFile.append("-per-" + frmtdtxtfldPercentage.getValue());
                    sbDestinationsFile.append("-seed-1.dat");
                    db.generateDifferentDistance(((Number) frmtdtxtfldPercentage.getValue()).doubleValue(), 200,
                            100, 75);
                    break;
                case ("Medium"):
                    sbDestinationsFile.append("split-" + sliderAgent.getValue());
                    sbDestinationsFile.append("-dis-" + frmtdtxtfldDistance.getValue());
                    sbDestinationsFile.append("-ang-"
                            + String.format("%.2f", ((Number) frmtdtxtfldAngle.getValue()).doubleValue()));
                    sbDestinationsFile.append("-per-"
                            + String.format("%.3f", ((Number) frmtdtxtfldPercentage.getValue()).doubleValue()));
                    sbDestinationsFile.append("-seed-1.dat");
                    db.generateSplitNorth(((Number) frmtdtxtfldDistance.getValue()).doubleValue(),
                            ((Number) frmtdtxtfldAngle.getValue()).doubleValue(),
                            ((Number) frmtdtxtfldPercentage.getValue()).doubleValue());
                    break;
                case ("Maximum"):
                    sbDestinationsFile.append("poles-" + sliderAgent.getValue());
                    sbDestinationsFile.append("-per-" + frmtdtxtfldPercentage.getValue());
                    sbDestinationsFile.append("-seed-1.dat");
                    db.generatePoles(50, 100, ((Number) frmtdtxtfldPercentage.getValue()).doubleValue());
                    break;
                case ("Uninformed"):
                    sbDestinationsFile.append("split-poles-" + frmtdtxtfldInformedCount.getValue());
                    sbDestinationsFile.append("-dis-"
                            + String.format("%.1f", ((Number) frmtdtxtfldDistance.getValue()).doubleValue()));
                    sbDestinationsFile.append("-ang-"
                            + String.format("%.2f", ((Number) frmtdtxtfldAngle.getValue()).doubleValue()));
                    sbDestinationsFile.append("-per-"
                            + String.format("%.3f", ((Number) frmtdtxtfldPercentage.getValue()).doubleValue()));
                    sbDestinationsFile.append("-seed-1.dat");
                    db.generateSplitPoles(((Number) frmtdtxtfldDistance.getValue()).doubleValue(),
                            ((Number) frmtdtxtfldAngle.getValue()).doubleValue(),
                            ((Number) frmtdtxtfldPercentage.getValue()).doubleValue(),
                            ((Number) frmtdtxtfldInformedCount.getValue()).intValue());
                    break;
                default: //Should never happen
                    break;
                }
                _simulatorProperties.put("destinations-file", String.valueOf(sbDestinationsFile.toString()));

                _simulatorProperties.put("live-delay", String.valueOf(15)); //Doesn't change
                _simulatorProperties.put("results-dir", "results"); //Doesn't change

                new Thread(new Runnable() {
                    public void run() {
                        try {
                            runSimulation();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }

    });
    panelStartButtons.add(btnStartSimulation);

    JButton btnStartSimulationFrom = new JButton("Run Simulation from Properties File");
    btnStartSimulationFrom
            .setToolTipText("Runs the simulator with the values provided in the properties file.");
    btnStartSimulationFrom.setEnabled(false);
    panelStartButtons.add(btnStartSimulationFrom);

    panelTab3.add(panelStartButtons);
}

From source file:canreg.client.analysis.AgeSpecificCasesPerHundredThousandTableBuilder.java

@Override
public LinkedList<String> buildTable(String tableHeader, String reportFileName, int startYear, int endYear,
        Object[][] incidenceData, PopulationDataset[] populations, PopulationDataset[] standardPopulations,
        LinkedList<ConfigFields> configList, String[] engineParameters, FileTypes fileType)
        throws NotCompatibleDataException {

    LinkedList<String> generatedFiles = new LinkedList<String>();

    String footerString = java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("TABLE BUILT ")
            + new Date()
            + java.util.ResourceBundle
                    .getBundle(/*from   w  w  w  .j  a  va  2  s  .  co m*/
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                    .getString(" BY CANREG5.");

    String notesString = "";

    double tableFontSize = 7.5;
    String font = "Times";

    int[] years = { startYear, endYear };

    double casesArray[][][] = null; // a 3D array of sex, icd and agegroup - with one extra layer in all dimensions containing a sum of all
    double populationArray[][] = null; // contains population count in the following format: [sex][agegroup]

    //      double RegPop[][];
    double totalCasesPerHundredThousand[][];
    double crudeRate[][];
    double MV[][];
    double ASR[][];
    double ASRbyAgeGroup[][][];
    double ratei[][];
    //      double vASR[][];
    double ASRluL[][][];
    double variL[][];
    double variLbyAgeGroup[][][];
    double DCO[][];

    char ASRf[][];
    double ASRratio[][];
    char MVf[][];

    String sexLabel[] = null;
    String tableLabel[] = null;
    String icdLabel[] = null;

    LinkedList cancerGroupsLocal[] = null;

    LinkedList<FieldDescription> incidenceFieldDescriptionList = null;

    boolean showSeeNotesNote = true;

    char Childc[][] = new char[2][3];

    double casesPerHundredThousand[][][];

    double cumRate64[][];
    double cumRate74[][];

    tableLabel = ConfigFieldsReader.findConfig("table_label", configList);
    // sexLabel = ConfigFieldsReader.findConfig("sex_label", configList);

    sexLabel = new String[] {
            java.util.ResourceBundle.getBundle("canreg/client/analysis/resources/AbstractEditorialTableBuilder")
                    .getString("MALE"),
            java.util.ResourceBundle.getBundle("canreg/client/analysis/resources/AbstractEditorialTableBuilder")
                    .getString("FEMALE") };

    icdLabel = ConfigFieldsReader.findConfig("ICD_groups_labels", configList);
    icd10GroupDescriptions = ConfigFieldsReader.findConfig("ICD10_groups", configList);

    cancerGroupsLocal = EditorialTableTools.generateICD10Groups(icd10GroupDescriptions);

    allCancerGroupsIndex = EditorialTableTools.getICD10index("ALL", icd10GroupDescriptions);

    leukemiaNOSCancerGroupIndex = EditorialTableTools.getICD10index(950, cancerGroupsLocal);

    skinCancerGroupIndex = EditorialTableTools.getICD10index("C44", icd10GroupDescriptions);

    bladderCancerGroupIndex = EditorialTableTools.getICD10index("C67", icd10GroupDescriptions);

    mesotheliomaCancerGroupIndex = EditorialTableTools.getICD10index("C45", icd10GroupDescriptions);

    kaposiSarkomaCancerGroupIndex = EditorialTableTools.getICD10index("C46", icd10GroupDescriptions);

    myeloproliferativeDisordersCancerGroupIndex = EditorialTableTools.getICD10index("MPD",
            icd10GroupDescriptions);

    myelodysplasticSyndromesCancerGroupIndex = EditorialTableTools.getICD10index("MDS", icd10GroupDescriptions);

    allCancerGroupsButSkinIndex = EditorialTableTools.getICD10index("ALLbC44", icd10GroupDescriptions);

    leukemiaNOSCancerGroupIndex = EditorialTableTools.getICD10index(950, cancerGroupsLocal);

    brainAndCentralNervousSystemCancerGroupIndex = EditorialTableTools.getICD10index("C70-72",
            icd10GroupDescriptions);

    ovaryCancerGroupIndex = EditorialTableTools.getICD10index(569, cancerGroupsLocal);

    otherCancerGroupsIndex = EditorialTableTools.getICD10index("O&U", icd10GroupDescriptions);

    numberOfCancerGroups = cancerGroupsLocal.length;

    lineBreaks = parseLineBreaks(ConfigFieldsReader.findConfig("line_breaks", configList));

    numberOfYears = years[1] - years[0] + 1;

    minimumCasesLimit = minimumCasesPerYearLimit * numberOfYears;

    noOldData = true;

    casesPerHundredThousand = new double[numberOfSexes][numberOfAgeGroups][numberOfCancerGroups];

    casesArray = new double[numberOfCancerGroups][numberOfSexes][numberOfAgeGroups];

    cumRate64 = new double[numberOfSexes][numberOfCancerGroups];
    cumRate74 = new double[numberOfSexes][numberOfCancerGroups];

    populationArray = new double[numberOfSexes][numberOfAgeGroups];
    foundAgeGroups = new boolean[numberOfAgeGroups];

    if (areThesePopulationDatasetsCompatible(populations)) {
        for (PopulationDataset population : populations) {
            population.addPopulationDataToArrayForTableBuilder(populationArray, foundAgeGroups,
                    new AgeGroupStructure(5, 85, 1));
        }
    } else {
        throw new NotCompatibleDataException();
    }

    populationString = populations[0].getPopulationDatasetName();

    int lastCommaPlace = populationString.lastIndexOf(",");

    if (lastCommaPlace != -1) {
        populationString = populationString.substring(0, lastCommaPlace);
    }

    if (populations[0].getFilter().length() > 0) {
        notesString = java.util.ResourceBundle
                .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                .getString("FILTER USED:") + " " + populations[0].getFilter();
    }

    if (populations.length > 0) {
        notesString += ", "
                + java.util.ResourceBundle.getBundle(
                        "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                        .getString("REFERENCE POPULATION:")
                + " " + populations[0].getReferencePopulation().getPopulationDatasetName();
    }

    standardPopulationArray = new double[numberOfSexes][numberOfAgeGroups];
    for (PopulationDataset stdPopulation : standardPopulations) {
        stdPopulation.addPopulationDataToArrayForTableBuilder(standardPopulationArray, null,
                new AgeGroupStructure(5, 85, 1));
    }

    // standardize population array
    for (int sexNumber = 0; sexNumber < numberOfSexes; sexNumber++) {
        for (int ageGroupNumber = 0; ageGroupNumber < numberOfAgeGroups; ageGroupNumber++) {
            standardPopulationArray[sexNumber][ageGroupNumber] = (standardPopulationArray[sexNumber][ageGroupNumber]
                    / standardPopulationArray[sexNumber][numberOfAgeGroups - 1]) * 100000;
        }
    }

    highestPopulationAgeGroup = findHighestAgeGroup(foundAgeGroups);
    lowestPopulationAgeGroup = findLowestAgeGroup(foundAgeGroups);

    int records = 0;
    // generate statistics

    // Generate based on death certificate only
    DCO = new double[numberOfSexes][numberOfCancerGroups];

    // and microscopical verification
    MV = new double[numberOfSexes][numberOfCancerGroups];

    String sexString;
    String icdString;
    String morphologyString;
    String yearString;
    String ageString;
    String basisString;
    String casesString;

    int sex, icdNumber, year, icdIndex, yearIndex, ageGroup, ageInt, basis, cases;

    if (incidenceData != null) {
        for (Object[] line : incidenceData) {
            try {

                // Set default
                icdIndex = -1;
                cases = 0;

                // Unknown sex group = 3
                sex = 3;
                // Extract data
                sexString = (String) line[SEX_COLUMN];
                sex = Integer.parseInt(sexString.trim());

                // sex = 3 is unknown sex
                if (sex > 2) {
                    sex = 3;
                }

                morphologyString = (String) line[MORPHOLOGY_COLUMN];

                /*
                if (morphologyString.length() > 0) {
                int morphology = Integer.parseInt(morphologyString);
                if (morphology == 9140) {
                String behaviourString = getContentOfField(
                incidenceFieldDescriptionList,
                "behaviour", line).trim();
                if (behaviourString.equals("3")) {
                icdIndex = kaposiSarkomaCancerGroupIndex;
                }
                        
                } else if ((int)(morphology/10) == 905) {
                String behaviourString = getContentOfField(incidenceFieldDescriptionList,
                "behaviour", line).trim();
                if (behaviourString.equals("3")) {
                icdIndex = mesotheliomaCancerGroupIndex;
                }
                }
                }
                 */
                if (icdIndex < 0) {
                    icdString = (String) line[ICD10_COLUMN];
                    if (icdString.length() > 0 && icdString.trim().substring(0, 1).equals("C")) {
                        icdString = icdString.trim().substring(1);
                        icdNumber = Integer.parseInt(icdString);
                        if (icdString.length() < 3) {
                            icdNumber = icdNumber * 10;
                        }
                        icdIndex = EditorialTableTools.getICD10index(icdNumber, cancerGroupsLocal);
                        if (icdIndex == -1) {
                            icdIndex = -1;
                        }
                    } else if (icdString.length() > 0 && icdString.trim().substring(0, 1).equals("D")) {
                        icdString = icdString.trim().substring(1);
                        icdNumber = Integer.parseInt(icdString);
                        if (icdString.length() < 3) {
                            icdNumber = icdNumber * 10;
                        }
                        if (icdNumber == 90 || icdNumber == 414) {
                            icdIndex = bladderCancerGroupIndex;
                        } else if ((int) (icdNumber / 10) == 45 || (int) (icdNumber / 10) == 47) {
                            icdIndex = myeloproliferativeDisordersCancerGroupIndex;
                        } else if ((int) (icdNumber / 10) == 46) {
                            icdIndex = myelodysplasticSyndromesCancerGroupIndex;
                        } else {
                            icdIndex = DONT_COUNT;
                        }
                    }

                }

                yearString = line[YEAR_COLUMN].toString();
                year = Integer.parseInt(yearString);
                yearIndex = year - years[0];
                ageString = line[AGE_COLUMN].toString();
                ageInt = Integer.parseInt(ageString);

                if (ageInt == unknownAgeInt) {
                    ageGroup = unknownAgeGroupIndex;
                } else {
                    ageGroup = populations[yearIndex].getAgeGroupIndex(ageInt);
                    // Adjust age group
                    if (populations[yearIndex].getAgeGroupStructure().getSizeOfFirstGroup() != 1) {
                        ageGroup += 1;
                    }
                }

                // Extract cases
                cases = (Integer) line[CASES_COLUMN];

                if (icdIndex != DONT_COUNT && year <= years[1] && year >= years[0]) {

                    // Basis of diagnosis
                    basisString = line[BASIS_DIAGNOSIS_COLUMN].toString();
                    if (basisString != null) {
                        basis = Integer.parseInt(basisString.trim());
                    } else {
                        basis = -1;
                    }

                    if (sex <= numberOfSexes && icdIndex >= 0 && icdIndex <= cancerGroupsLocal.length) {

                        casesArray[icdIndex][sex - 1][ageGroup] += cases;

                        //
                        if (basis == 00) {
                            DCO[sex - 1][icdIndex] += cases;
                        } else if (basis >= 10 && basis <= 19) {
                            MV[sex - 1][icdIndex] += cases;
                        }
                    } else if (otherCancerGroupsIndex >= 0) {
                        casesArray[otherCancerGroupsIndex][sex - 1][ageGroup] += cases;
                    }
                    if (allCancerGroupsIndex >= 0) {
                        casesArray[allCancerGroupsIndex][sex - 1][ageGroup] += cases;
                        if (basis == 0) {
                            DCO[sex - 1][allCancerGroupsIndex] += cases;
                        } else if (basis >= 10 && basis <= 19) {
                            MV[sex - 1][allCancerGroupsIndex] += cases;
                        }
                    }
                    if (allCancerGroupsButSkinIndex >= 0 && skinCancerGroupIndex >= 0
                            && icdIndex != skinCancerGroupIndex) {
                        casesArray[allCancerGroupsButSkinIndex][sex - 1][ageGroup] += cases;
                        if (basis == 0) {
                            DCO[sex - 1][allCancerGroupsButSkinIndex] += cases;
                        } else if (basis >= 10 && basis <= 19) {
                            MV[sex - 1][allCancerGroupsButSkinIndex] += cases;
                        }
                    }
                    records += cases;
                    if (records % recordsPerFeedback == 0) {
                        System.out.println(java.util.ResourceBundle.getBundle(
                                "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                                .getString("PROCESSING RECORD NUMBER: ") + records);
                    }
                }
            } catch (NumberFormatException nfe) {
                Logger.getLogger(AgeSpecificCasesPerHundredThousandTableBuilder.class.getName())
                        .log(Level.WARNING, null, nfe);
            }
            // Read next line

        }
    }
    System.out.println(java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("PROCESSED ")
            + records
            + java.util.ResourceBundle
                    .getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                    .getString(" RECORDS."));

    // Get our matrixes ready
    // Age standarized rate
    ASR = new double[numberOfSexes][numberOfCancerGroups];
    ASRbyAgeGroup = new double[numberOfSexes][numberOfCancerGroups][numberOfAgeGroups];
    ASRluL = new double[numberOfSexes][numberOfCancerGroups][2];
    variL = new double[numberOfSexes][numberOfCancerGroups];
    variLbyAgeGroup = new double[numberOfSexes][numberOfCancerGroups][numberOfAgeGroups];

    // Total casesPerHundredThousand
    totalCasesPerHundredThousand = new double[numberOfSexes][numberOfCancerGroups];
    // Crude rate
    crudeRate = new double[numberOfSexes][numberOfCancerGroups];

    for (int sexNumber = 0; sexNumber < 2; sexNumber++) {

        // The age groups
        ageLabel[lowestPopulationAgeGroup] = "0-";

        for (int icdGroup = 0; icdGroup < numberOfCancerGroups; icdGroup++) {
            if (icdLabel[icdGroup].substring(0 + sexNumber, 1 + sexNumber).equalsIgnoreCase("1")) {
                // The age groups

                double previousAgeGroupCases = 0;
                double previousAgeGroupPopulation = 0;
                double previousAgeGroupWstdPopulation = 0;

                double lastAgeGroupCases = 0;
                double lastAgeGroupPopulation = 0;
                double lastAgeGroupWstdPopulation = 0;

                for (int ageGroupNumber = 1; ageGroupNumber < unknownAgeGroupIndex; ageGroupNumber++) {
                    if (ageGroupNumber == 1) {
                        for (int ag = lowestIncidenceAgeGroup; ag < ageGroupNumber; ag++) {
                            previousAgeGroupCases += casesArray[icdGroup][sexNumber][ag];
                            previousAgeGroupPopulation += populationArray[sexNumber][ag];
                            previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ag];
                        }
                    }
                    if (foundAgeGroups[ageGroupNumber] && ageGroupNumber < highestPopulationAgeGroup) {
                        casesPerHundredThousand[sexNumber][ageGroupNumber][icdGroup] = 100000
                                * (casesArray[icdGroup][sexNumber][ageGroupNumber] + previousAgeGroupCases)
                                / (populationArray[sexNumber][ageGroupNumber] + previousAgeGroupPopulation);

                        previousAgeGroupCases = 0;
                        previousAgeGroupPopulation = 0;
                        previousAgeGroupWstdPopulation = 0;

                    } else {
                        previousAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                        previousAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                        previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];
                    }
                }
                // We calculate the "leftovers" from the last age group
                if (previousAgeGroupPopulation > 0) {
                    casesPerHundredThousand[sexNumber][highestPopulationAgeGroup][icdGroup] = 100000
                            * (previousAgeGroupCases) / (previousAgeGroupPopulation);

                }

                previousAgeGroupCases = 0;
                previousAgeGroupPopulation = 0;
                previousAgeGroupWstdPopulation = 0;

            }
        }
    }

    // ASR, vASR, MV, MI, DCO
    for (int sexNumber = 0; sexNumber < numberOfSexes; sexNumber++) {
        for (int icdGroup = 0; icdGroup < numberOfCancerGroups; icdGroup++) {

            double previousAgeGroupCases = 0;
            double previousAgeGroupPopulation = 0;
            double previousAgeGroupWstdPopulation = 0;

            double lastAgeGroupCases = 0;
            double lastAgeGroupPopulation = 0;
            double lastAgeGroupWstdPopulation = 0;

            totalCasesPerHundredThousand[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][0];

            for (int ageGroupNumber = 1; ageGroupNumber < unknownAgeGroupIndex; ageGroupNumber++) {
                if (ageGroupNumber == 1) {
                    for (int ag = lowestIncidenceAgeGroup; ag < ageGroupNumber; ag++) {
                        previousAgeGroupCases += casesArray[icdGroup][sexNumber][ag];
                        previousAgeGroupPopulation += populationArray[sexNumber][ag];
                        previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ag];
                    }
                }
                if (foundAgeGroups[ageGroupNumber] && ageGroupNumber < highestPopulationAgeGroup
                        && (previousAgeGroupPopulation + populationArray[sexNumber][ageGroupNumber] > 0)) {
                    double asr = calculateASR(
                            (previousAgeGroupCases + casesArray[icdGroup][sexNumber][ageGroupNumber]),
                            (previousAgeGroupPopulation + populationArray[sexNumber][ageGroupNumber]),
                            (previousAgeGroupWstdPopulation
                                    + standardPopulationArray[sexNumber][ageGroupNumber]));

                    ASR[sexNumber][icdGroup] += asr;

                    ASRbyAgeGroup[sexNumber][icdGroup][ageGroupNumber] = asr;

                    /* We don't use confidence intervals so this was removed 16.07.07
                    double varil =
                    calculateVariL((previousAgeGroupCases +
                    casesArray[icdGroup][sex][
                    ageGroup]),
                    (previousAgeGroupWstdPopulation +
                    wstdPop[ageGroup]),
                    (previousAgeGroupPopulation +
                    populationArray[sex][ageGroup])
                    );
                            
                    variL[sex][icdGroup] += varil;
                    variLbyAgeGroup[sex][icdGroup][ageGroup] = varil;
                     */
                    previousAgeGroupCases = 0;
                    previousAgeGroupPopulation = 0;
                    previousAgeGroupWstdPopulation = 0;

                } else if (ageGroupNumber < highestPopulationAgeGroup) {
                    previousAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                    previousAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                    previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];

                } else {
                    lastAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                    lastAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                    lastAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];
                }

                totalCasesPerHundredThousand[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][ageGroupNumber];
            }

            // We calculate the "leftovers" from the last age group
            if (lastAgeGroupPopulation > 0) {
                double asr = calculateASR(lastAgeGroupCases, lastAgeGroupPopulation,
                        lastAgeGroupWstdPopulation);
                ASR[sexNumber][icdGroup] += asr;

                ASRbyAgeGroup[sexNumber][icdGroup][highestPopulationAgeGroup] = asr;
                /* We don't use confidence intervals so this was removed 16.07.07
                double varil = calculateVariL(lastAgeGroupCases,
                lastAgeGroupWstdPopulation, lastAgeGroupPopulation);
                        
                variL[sex][icdGroup] += varil;
                        
                variLbyAgeGroup[sex][icdGroup][highestPopulationAgeGroup] =
                varil;
                 */

            }

            // and take the unknown age group into account
            totalCasesPerHundredThousand[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][unknownAgeGroupIndex];

            if (totalCasesPerHundredThousand[sexNumber][icdGroup] > 0) {

                DCO[sexNumber][icdGroup] = 100 * (int) DCO[sexNumber][icdGroup]
                        / totalCasesPerHundredThousand[sexNumber][icdGroup];
                MV[sexNumber][icdGroup] = 100 * (int) MV[sexNumber][icdGroup]
                        / totalCasesPerHundredThousand[sexNumber][icdGroup];
                crudeRate[sexNumber][icdGroup] = totalCasesPerHundredThousand[sexNumber][icdGroup]
                        * standardPopulationArray[sexNumber][allAgeGroupsIndex]
                        / (populationArray[sexNumber][allAgeGroupsIndex]);

                /* We don't use confidence intervals so this was removed 16.07.07
                double[] asrlul = calculateASRluL(ASR[sex][icdGroup],
                variL[sex][icdGroup], wstdPop[allAgeGroupsIndex]);
                        
                ASRluL[sex][icdGroup][0] = asrlul[0];
                ASRluL[sex][icdGroup][1] = asrlul[1];
                 */
                // Cum. Rates
                if (highestPopulationAgeGroup > 13) {
                    for (int k = 1; k <= 13; k++) {
                        cumRate64[sexNumber][icdGroup] += casesPerHundredThousand[sexNumber][k][icdGroup]
                                * cumPop18[k] / 1000.0;
                    }
                }
                if (highestPopulationAgeGroup > 15) {
                    for (int k = 1; k <= 15; k++) {
                        cumRate74[sexNumber][icdGroup] += casesPerHundredThousand[sexNumber][k][icdGroup]
                                * cumPop18[k] / 1000.0;
                    }
                }

                // adjust the ASR and cum rates for unknown ages
                if (ASR[sexNumber][icdGroup] > 0) {
                    double ratio = totalCasesPerHundredThousand[sexNumber][icdGroup]
                            / (totalCasesPerHundredThousand[sexNumber][icdGroup]
                                    - casesArray[icdGroup][sexNumber][unknownAgeGroupIndex]);
                    ASR[sexNumber][icdGroup] *= ratio;
                    cumRate64[sexNumber][icdGroup] *= ratio;
                    cumRate74[sexNumber][icdGroup] *= ratio;

                }
                /*                    if (!isSpecialized) {
                cumRate64[sex][allCancerGroupsIndex] += cumRate64[sex][icdGroup];
                cumRate74[sex][allCancerGroupsIndex] += cumRate74[sex][icdGroup];
                if (icdGroup!=skinCancerGroupIndex) {
                cumRate64[sex][allCancerGroupsIndex] += cumRate64[sex][icdGroup];
                cumRate74[sex][allCancerGroupsIndex] += cumRate74[sex][icdGroup];
                }
                }
                 */
            }
        }
    }

    // Get our matrixes ready
    ASRf = new char[numberOfSexes][numberOfCancerGroups];

    // Adjust the age labels
    ageLabel[1] = "0-";
    ageLabel[highestPopulationAgeGroup] = ageLabel[highestPopulationAgeGroup].substring(0,
            ageLabel[highestPopulationAgeGroup].length() - 1) + "+";

    // Write it out
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(1);
    nf.setMinimumFractionDigits(1);

    // Writing
    System.out.println(java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("WRITING DATA...\\N"));

    Writer reportFileWriter;

    if (fileType.equals(FileTypes.csv)) {
        // write tab separated stuff here
        // CSVWriter csvOut;
        CSVPrinter csvOut;

        for (int sexNumber = 0; sexNumber < numberOfSexes - 1; sexNumber++) {
            try {
                String tabReportFileName = "";
                try {
                    tabReportFileName = reportFileName + sexLabel[sexNumber] + ".csv";
                    System.out.println(java.util.ResourceBundle.getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                            .getString("WRITING TO ") + tabReportFileName);
                    reportFileWriter = new OutputStreamWriter(new FileOutputStream(tabReportFileName), "UTF-8");
                } catch (IOException ioe) {
                    System.out.println(java.util.ResourceBundle.getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                            .getString("ERROR IN REPORTFILE: ") + tabReportFileName);
                    reportFileWriter = new OutputStreamWriter(System.out);
                }
                // reportStream = new PrintStream(tabReportFileName);
                // write the header line
                LinkedList<String> headers = new LinkedList<String>();
                headers.add("SITE");
                headers.add("ALL AGES");
                headers.add("AGE UNK");
                // add age groups

                for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                    headers.add(ageLabel[age]);
                }

                headers.add("CRUDE RATE");
                headers.add("(%)");
                headers.add("CUM 0-64");
                headers.add("CUM 0-74");
                headers.add("ASR");
                headers.add("ICD (10th)");
                //                csvOut.writeNext(line.toArray(new String[0]));
                CSVFormat format = CSVFormat.DEFAULT.withDelimiter(',')
                        .withHeader(headers.toArray(new String[0]));

                csvOut = new CSVPrinter(reportFileWriter, format);
                //                    csvOut.printRecord(headers);

                LinkedList<String> line = new LinkedList<String>();
                // write the data
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        line.add(icdLabel[j].substring(3));
                        line.add(formatNumber(totalCasesPerHundredThousand[sexNumber][j], 0));
                        line.add(formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0));
                        for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                            if (casesPerHundredThousand[sexNumber][age][j] > 0) {
                                line.add(formatNumber(casesPerHundredThousand[sexNumber][age][j]));
                            } else {
                                line.add("0.0");
                            }
                        }
                        line.add(formatNumber(crudeRate[sexNumber][j], 2));
                        line.add(formatNumber(100 * totalCasesPerHundredThousand[sexNumber][j]
                                / totalCasesPerHundredThousand[sexNumber][allCancerGroupsButSkinIndex]));
                        line.add(formatNumber(cumRate64[sexNumber][j], 2));
                        line.add(formatNumber(cumRate74[sexNumber][j], 2));
                        line.add(formatNumber(ASR[sexNumber][j]));
                        line.add(icd10GroupDescriptions[j]);
                        csvOut.printRecord(line);
                        line.clear();
                    }
                }

                csvOut.flush();
                csvOut.close();
                generatedFiles.add(tabReportFileName);
            } catch (IOException ex) {
                Logger.getLogger(AgeSpecificCasesPerHundredThousandTableBuilder.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    } // Make PS-file
    else {
        for (int sexNumber = 0; sexNumber < numberOfSexes - 1; sexNumber++) {
            String psFileName = reportFileName + "-" + sexLabel[sexNumber] + ".ps";
            generatedFiles.add(psFileName);
            try {
                Writer fw = new OutputStreamWriter(new FileOutputStream(psFileName), "UTF-8");
                nf.setMaximumFractionDigits(1);
                nf.setMinimumFractionDigits(1);

                fw.write("/RLT {rlineto} def\n");
                fw.write("/LT {lineto} def\n");
                fw.write("/MT {moveto} def\n");
                fw.write("/SCF {scalefont} def\n");
                fw.write("/SF {setfont} def\n");
                fw.write("/SG {setgray} def\n");
                fw.write("/FF {findfont} def\n");
                fw.write("/SLW {setlinewidth} def\n");
                fw.write("/CP {closepath} def\n");
                fw.write("/Mainfont\n");
                fw.write("/Helvetica-Bold FF " + (int) (tableFontSize * 2 - 3) + " SCF def\n");
                fw.write("/Titlefont\n");
                fw.write("/Helvetica FF " + tableFontSize + " SCF def\n");
                fw.write("/Tablefont\n");
                fw.write("/" + font + " FF " + tableFontSize + " SCF def\n");
                fw.write("/ASRfont\n");
                fw.write("/" + font + "-Bold FF " + tableFontSize + " SCF def\n");
                fw.write("/ICDfont\n");
                fw.write("/" + font + "-Italic FF " + tableFontSize + " SCF def\n");
                fw.write("/ASRitalicsfont\n");
                fw.write("/" + font + "-Italic-Bold FF " + tableFontSize + " SCF def\n");
                fw.write("/col 735 def\n");
                fw.write("/RS {dup stringwidth pop col exch sub 0 rmoveto show} def\n");
                fw.write("/CS {dup stringwidth pop 810 exch sub 2 div 0 rmoveto show} def\n");
                fw.write("/nstr 1 string def\n");
                fw.write("/prtchar {nstr 0 3 -1 roll put nstr show} def\n");
                fw.write("newpath\n");
                fw.write("90 rotate -20 -570 translate\n"); //  Landscape
                fw.write("Mainfont SF\n");
                fw.write("0 535 MT (" + tableHeader + ") CS\n");
                fw.write("Titlefont SF\n");
                fw.write("0 525 MT (" + populationString + ") CS\n");
                fw.write("0 513 MT (" + tableLabel[0] + " - " + sexLabel[sexNumber] + ") CS\n");
                //                                                                                              draw the grey frame
                fw.write("0.85 SG 27 510 translate\n");
                fw.write("0 -5 MT 785 -5 LT 785 -27 LT 0 -27 LT  CP fill\n");
                fw.write("0 -510 translate 0.95 SG\n");
                double k = 475;

                for (int icd = 0; icd < numberOfCancerGroups; icd++) {
                    if ((icd + 1) < numberOfCancerGroups && icdLabel[icd + 1].charAt(sexNumber) == '1') {
                        int lines = (isLineBreak(icd));
                        if (lines > 0) {
                            k -= 2;
                            fw.write("0 " + (k - 2) + " MT 785 " + (k - 2) + " LT 785 "
                                    + (k - 2 - (lines * (tableFontSize))) + " LT 0 "
                                    + (k - 2 - (lines * (tableFontSize))) + " LT CP fill\n");
                        } else if (lines < 0) {
                            k -= 2;
                        }
                        k -= tableFontSize;
                    }
                }

                /*
                for (int j = 0; j < numberOfCancerGroups; j++) {
                if (icdLabel[j].charAt(sex) == '1') {
                        
                int lines = (isLineBreak(j));
                if (lines > 0) {
                k -= 2;
                        
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - lines * tableFontSize) + " LT 0 " + (k - lines * tableFontSize) +
                " LT CP fill\n");
                        
                } else if (lines > 0)
                k -= 2;
                k -= lines * tableFontSize;
                        
                        
                        
                        
                if (IsLineBreak(j)) {
                k -= 2;
                }
                //  draw the grey frames
                if (j == 8) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 35) + " LT 0 " + (k - 35) +
                " LT CP fill\n");
                } else if (j == 34) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 26) + " LT 0 " + (k - 26) +
                " LT CP fill\n");
                } else if (j == 16 || j == 22 || j == 40) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 18) + " LT 0 " + (k - 18) +
                " LT CP fill\n");
                } else if (j == 27) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 42) + " LT 0 " + (k - 42) +
                " LT CP fill\n");
                } else if (j == 47) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 34) + " LT 0 " + (k - 34) +
                " LT CP fill\n");
                } else if (j == 53) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 12) + " LT 0 " + (k - 12) +
                " LT CP fill\n");
                }
                k -= (tableFontSize);
                }
                        
                }
                 */
                fw.write("0 SG\n");

                fw.write("ICDfont SF\n");
                fw.write(" 740 496 MT (ICD) show\n");
                fw.write(" 740 487 MT ((10th)) show\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("ICDfont SF\n");
                        }

                        fw.write("745 " + k + " MT (" + icd10GroupDescriptions[j] + ") show\n");
                        k -= (tableFontSize);
                    }
                }

                fw.write("/col col 0 sub def\n");
                fw.write("ASRfont SF\n");
                fw.write("0 496 MT (ASR) RS\n");
                fw.write("0 487 MT ( ) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ASRitalicsfont SF\n");
                        } else {
                            fw.write("ASRfont SF\n");
                        }

                        fw.write("0 " + k + " MT (" + formatNumber(ASR[sexNumber][j]) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }

                fw.write("/col col 20 sub def\n");
                fw.write("Tablefont SF\n");
                fw.write("0 496 MT (CUM) RS\n");
                fw.write("0 487 MT (0-74) RS\n");
                k = 475;
                if (cumRate74[sexNumber][allCancerGroupsIndex] > 0) {
                    for (int j = 0; j < numberOfCancerGroups; j++) {
                        if (icdLabel[j].charAt(sexNumber) == '1') {
                            if (isLineBreak(j - 1) != 0) {
                                k -= 2;
                            }
                            if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                    || j == bladderCancerGroupIndex
                                    || j == myelodysplasticSyndromesCancerGroupIndex
                                    || j == myeloproliferativeDisordersCancerGroupIndex
                                    || j == brainAndCentralNervousSystemCancerGroupIndex) {
                                fw.write("ICDfont SF\n");
                            } else {
                                fw.write("Tablefont SF\n");
                            }

                            fw.write("0 " + k + " MT (" + formatNumber(cumRate74[sexNumber][j], 2) + ") RS\n");
                            k -= (tableFontSize);
                        }
                    }
                }

                fw.write("/col col 20 sub def\n");
                fw.write("Tablefont SF\n");
                fw.write("0 496 MT (CUM) RS\n");
                fw.write("0 487 MT (0-64) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT (" + formatNumber(cumRate64[sexNumber][j], 2) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                /* No MVs shown
                fw.write("Tablefont SF\n");
                fw.write("/col col 20 sub def\n");
                fw.write("0 496 MT (MV) RS\n");
                fw.write("0 487 MT ((%)) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                if (icdLabel[j].charAt(sex) == '1') {
                if (isLineBreak(j - 1)!=0) {
                k -= 2;
                }
                        
                if (j==skinCancerGroupIndex || j == ovaryCancerGroupIndex || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex ||
                j == myeloproliferativeDisordersCancerGroupIndex || j == brainAndCentralNervousSystemCancerGroupIndex) {
                fw.write("ICDfont SF\n");
                } else fw.write("Tablefont SF\n");
                        
                if (CA[sex][j] >= 0) {
                fw.write("0 " + k + " MT (" +
                formatNumber(MV[sex][j]) + ") RS\n");
                } else {
                fw.write("0 " + k + " MT (      -) RS\n");
                }
                k -= (tableFontSize);
                }
                }
                 */
                fw.write("/col col 20 sub def\n");
                fw.write("0 491 MT ((%)) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }

                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        if (j != allCancerGroupsIndex && allCancerGroupsButSkinIndex >= 0) {
                            fw.write("0 " + k + " MT (" + formatNumber(100
                                    * totalCasesPerHundredThousand[sexNumber][j]
                                    / totalCasesPerHundredThousand[sexNumber][allCancerGroupsButSkinIndex])
                                    + ") RS\n");
                        }
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col col 20 sub def\n");
                fw.write("0 496 MT (CRUDE) RS\n");
                fw.write("0 487 MT (RATE) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT (" + formatNumber(crudeRate[sexNumber][j]) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col 119 def\n");
                fw.write("0 496 MT (ALL) RS\n");
                fw.write("0 487 MT (AGES) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT ("
                                + formatNumber(totalCasesPerHundredThousand[sexNumber][j], 0) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col col 20 add def\n");
                fw.write("0 496 MT (AGE) RS\n");
                fw.write("0 487 MT (UNK) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT ("
                                + formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }

                if (highestPopulationAgeGroup == numberOfAgeGroups - 4) {
                    fw.write("/col 145 def\n");
                } else if (highestPopulationAgeGroup == numberOfAgeGroups - 5) {
                    fw.write("/col 176 def\n");
                } else if (highestPopulationAgeGroup == numberOfAgeGroups - 6) {
                    fw.write("/col 208 def\n");
                } else {
                    fw.write("/col 145 def\n");
                }

                for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                    fw.write("/col col 26 add def\n");
                    fw.write("0 491 MT (" + ageLabel[age] + ") RS\n");
                    // fw.write("/col col 5 sub def\n");
                    k = 475;
                    for (int j = 0; j < numberOfCancerGroups; j++) {
                        if (icdLabel[j].charAt(sexNumber) == '1') {
                            if (isLineBreak(j - 1) != 0) {
                                k -= 2;
                            }

                            if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                    || j == bladderCancerGroupIndex
                                    || j == myelodysplasticSyndromesCancerGroupIndex
                                    || j == myeloproliferativeDisordersCancerGroupIndex
                                    || j == brainAndCentralNervousSystemCancerGroupIndex) {
                                fw.write("ICDfont SF\n");
                            } else {
                                fw.write("Tablefont SF\n");
                            }

                            if (casesPerHundredThousand[sexNumber][age][j] > 0) {
                                fw.write("0 " + k + " MT ("
                                        + formatNumber(casesPerHundredThousand[sexNumber][age][j]) + ") RS\n");
                            } else {
                                fw.write("0 " + k + " MT (    -  ) RS\n");
                            }
                            k -= (tableFontSize);
                        }
                    }
                }
                fw.write("3 492 MT ( S I T E) show\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("3 " + k + " MT (" + icdLabel[j].substring(3) + ") show\n");
                        k -= (tableFontSize);
                    }
                }
                if (showSeeNotesNote) {
                    fw.write("3 0 MT (" + notesString + ") show\n");
                }

                // Write the footer
                fw.write("0 0 MT (" + footerString + ") CS\n");

                fw.write("showpage\n");
                System.out.println("Wrote " + psFileName + ".");
                fw.close();
            } catch (IOException ioe) {
                System.out.println(ioe);
            }
        }
    }

    if (fileType == FileTypes.pdf) {
        LinkedList<String> newlyGeneratedFiles = new LinkedList<String>();
        for (String fileN : generatedFiles) {
            PsToPdfConverter pstopdf = new PsToPdfConverter(gspath);
            newlyGeneratedFiles.add(pstopdf.convert(fileN));
            // delete the ps file
            File file = new File(fileN);
            file.delete();
        }
        generatedFiles = newlyGeneratedFiles;
    }

    System.out.println("Fini!");

    return generatedFiles;
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private Map<String, Object> createTimeseries(String userPrincipalName, DataSeriesSource dss,
        List<Filter> filters, GroupingImpl group, String timeResolution, Integer prepull,
        String graphTimeSeriesUrl, final Collection<Record> records, final List<Dimension> accumulations,
        final List<Dimension> timeseriesDenominators, String detectorClass, boolean includeDetails,
        boolean displayIntervalEndDate, GraphDataInterface graphData, TimeZone clientTimezone) {

    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, ResolutionHandler> resolutionHandlers = null;
    result.put("success", false);
    try {//from   w w w  .ja v  a2  s .  com
        GroupingDimension grpdim = dss.getGroupingDimension(group.getId());
        resolutionHandlers = grpdim.getResolutionsMap();
        String dateFieldName = group.getId();
        Date startDate = null;
        Date endDate = null;
        if (grpdim != null
                && (grpdim.getSqlType() == FieldType.DATE || grpdim.getSqlType() == FieldType.DATE_TIME)) {
            for (Filter f : filters) {
                if (f instanceof OneArgOpFilter) {
                    OneArgOpFilter of = (OneArgOpFilter) f;
                    if (of.getFilterId().equalsIgnoreCase(grpdim.getId())
                            && (of.getSqlSnippet("").contains(">="))) {
                        startDate = (Date) of.getArguments().get(0);
                    } else if (of.getFilterId().equalsIgnoreCase(grpdim.getId())
                            && (of.getSqlSnippet("").contains("<="))) {
                        endDate = (Date) of.getArguments().get(0);
                    }
                }
            }
        }
        //union accumulations to get all results
        List<Dimension> dimensions = new ArrayList<Dimension>(
                ControllerUtils.unionDimensions(accumulations, timeseriesDenominators));

        int timeOffsetMillies = 0;
        String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false");
        if (timezoneEnabledString.equalsIgnoreCase("true")) {
            timeOffsetMillies = (clientTimezone.getRawOffset() - clientTimezone.getDSTSavings())
                    - (TimeZone.getDefault().getRawOffset() - TimeZone.getDefault().getDSTSavings());
        }
        Calendar startDayCal = Calendar.getInstance(clientTimezone);
        startDayCal.setTime(startDate);
        startDayCal.add(Calendar.MILLISECOND, timeOffsetMillies);

        //get data grouped by group dimension
        List<AccumPoint> points = extractAccumulationPoints(userPrincipalName, dss, records,
                startDayCal.getTime(), endDate, dimensions, group, resolutionHandlers);
        if (points.size() > 0) {
            DateFormat dateFormat = getDateFormat(timeResolution); //dateFormat.setTimeZone(timezone);
            DateFormat tmpDateFormat = (DateFormat) dateFormat.clone();
            tmpDateFormat.setTimeZone(clientTimezone);

            // number format for level
            NumberFormat numFormat3 = NumberFormat.getNumberInstance();
            numFormat3.setMinimumFractionDigits(0);
            numFormat3.setMaximumFractionDigits(3);

            // number format for expected count
            NumberFormat numFormat1 = NumberFormat.getNumberInstance();
            numFormat1.setMinimumFractionDigits(0);
            numFormat1.setMaximumFractionDigits(1);

            Calendar cal = new GregorianCalendar();
            cal.setTime(startDayCal.getTime());
            //offset start date to match prepull offset
            if (timeResolution.equals("weekly")) {
                cal.add(Calendar.DATE, (7 * prepull));
            } else if (timeResolution.equals("daily")) {
                cal.add(Calendar.DATE, prepull);
            }
            Date queryStartDate = cal.getTime();

            //-- Handles Denominator Types -- //
            double[] divisors = new double[points.size()];
            double multiplier = 1.0;
            boolean percentBased = false;
            String yAxisLabel = messageSource.getDataSourceMessage("graph.count", dss);

            boolean isDetectionDetector = !NoDetectorDetector.class.getName().equalsIgnoreCase(detectorClass);

            //if there is a denominator we need to further manipulate the data
            if (timeseriesDenominators != null && !timeseriesDenominators.isEmpty()) {
                // divisor is the sum of timeseriesDenominators
                divisors = totalSeriesValues(points, timeseriesDenominators);
                multiplier = 100.0;
                percentBased = true;
                yAxisLabel = messageSource.getDataSourceMessage("graph.percent", dss);
            } else {
                //the query is for total counts
                Arrays.fill(divisors, 1.0);
            }

            double[][] allCounts = new double[accumulations.size()][];
            int[][] allColors = new int[accumulations.size()][];
            String[][] allAltTexts = new String[accumulations.size()][];
            String[] dates = new String[] { "" };
            double[][] allExpecteds = new double[accumulations.size()][];
            double[][] allLevels = new double[accumulations.size()][];
            String[][] allLineSetURLs = new String[accumulations.size()][];
            String[][] allSwitchInfo = new String[accumulations.size()][];
            String[] lineSetLabels = new String[accumulations.size()];
            boolean[] displayAlerts = new boolean[accumulations.size()];

            //get all results
            Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions());
            Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims);
            Collection<String> accIds = ControllerUtils.getDimensionIdsFromCollection(dss.getAccumulations());
            //remove extra accumulations in the result set using string ids
            dimIds.removeAll(accIds);

            //for each accumulation we run detection and gather results
            int aIndex = 0;
            for (Dimension accumulation : accumulations) {
                String accumId = accumulation.getId();

                // use display name if it has one, otherwise translate its ID
                String accumIdTranslated = accumulation.getDisplayName();
                if (accumIdTranslated == null) {
                    accumIdTranslated = messageSource.getDataSourceMessage(accumulation.getId(), dss);
                }

                TemporalDetectorInterface TDI = (TemporalDetectorInterface) DetectorHelper
                        .createObject(detectorClass);
                TemporalDetectorSimpleDataObject TDDO = new TemporalDetectorSimpleDataObject();

                int[] colors;
                double[] counts;
                String[] altTexts;
                double[] expecteds;
                double[] levels;
                String[] switchInfo;
                String[] urls;

                //pull the counts from the accum array points
                double[] seriesDoubleArray = generateSeriesValues(points, accumId);

                //run divisor before detection
                for (int i = 0; i < seriesDoubleArray.length; i++) {
                    double div = divisors[i];
                    if (div == 0) {
                        seriesDoubleArray[i] = 0.0;
                    } else {
                        seriesDoubleArray[i] = (seriesDoubleArray[i] / div) * multiplier;
                    }
                }

                //run detection
                TDDO.setCounts(seriesDoubleArray);
                TDDO.setStartDate(startDate);
                TDDO.setTimeResolution(timeResolution);

                try {
                    TDI.runDetector(TDDO);
                } catch (Exception e) {
                    String errorMessage = "Failure to create Timeseries";
                    if (e.getMessage() != null) {
                        errorMessage = errorMessage + ":<BR>" + e.getMessage();
                    }
                    result.put("message", errorMessage);
                    result.put("success", false);
                    return result;
                }

                TDDO.cropStartup(prepull);
                counts = TDDO.getCounts();
                int tddoLength = counts.length;

                if (!DAILY.equalsIgnoreCase(timeResolution)) {
                    //toggle between start date and end date
                    //TDDO.setDates(getOurDates(startDate, endDate, tddoLength, timeResolution));
                    TDDO.setDates(getOurDates(queryStartDate, endDate, tddoLength, timeResolution,
                            displayIntervalEndDate));
                }
                double[] tcolors = TDDO.getColors();

                Date[] tdates = TDDO.getDates();
                altTexts = TDDO.getAltTexts();
                expecteds = TDDO.getExpecteds();
                levels = TDDO.getLevels();
                switchInfo = TDDO.getSwitchInfo();
                colors = new int[tddoLength];
                dates = new String[tddoLength];
                urls = new String[tddoLength];

                //add the accumId for the current series
                dimIds.add(accumId);

                StringBuilder jsCall = new StringBuilder();
                jsCall.append("javascript:OE.report.datasource.showDetails({");
                jsCall.append("dsId:'").append(dss.getClass().getName()).append("'");
                //specify results
                jsCall.append(",results:[")
                        .append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'")).append(']');
                //specify accumId
                jsCall.append(",accumId:'").append(accumId).append("'");

                addJavaScriptFilters(jsCall, filters, dateFieldName);

                //this builds urls and hover texts
                int startDay = getWeekStartDay(resolutionHandlers);

                Calendar c = Calendar.getInstance(clientTimezone);

                //               Calendar curr = Calendar.getInstance();
                for (int i = 0; i < tddoLength; i++) {
                    colors[i] = (int) tcolors[i];

                    // For a time series data point, set time to be current server time
                    // This will allow us to convert this data point date object to be request timezone date
                    c.setTime(tdates[i]);
                    c.add(Calendar.MILLISECOND, timeOffsetMillies);

                    if (timeResolution.equals(WEEKLY)) {
                        dates[i] = dateFormatWeekPart.format(tdates[i]) + "-W"
                                + PgSqlDateHelper.getWeekOfYear(startDay, c) + "-"
                                + PgSqlDateHelper.getYear(startDay, c);
                    } else {
                        dates[i] = tmpDateFormat.format(c.getTime());
                    }

                    altTexts[i] = "(" + accumIdTranslated + ") " + // Accum
                            "Date: " + dates[i] + // Date
                            ", Level: " + numFormat3.format(levels[i]) + // Level
                            ", Count: " + ((int) counts[i]) + // Count
                            ", Expected: " + numFormat1.format(expecteds[i]); // Expected

                    if (switchInfo != null) {
                        altTexts[i] += ", Switch: " + switchInfo[i] + ", ";
                    }

                    // build the click through url
                    StringBuilder tmp = new StringBuilder(jsCall.toString());

                    // add the date field with start and end dates from the data point
                    if (!DAILY.equalsIgnoreCase(timeResolution)) {
                        Calendar timeSet = Calendar.getInstance(clientTimezone);
                        timeSet.setTime(tdates[i]);

                        if (WEEKLY.equalsIgnoreCase(timeResolution)) {
                            timeSet.set(Calendar.DAY_OF_WEEK, startDay + 1);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            timeSet.add(Calendar.DAY_OF_YEAR, 6);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        } else if (MONTHLY.equalsIgnoreCase(timeResolution)) {
                            // Compute last day of month
                            timeSet.set(Calendar.DAY_OF_MONTH, 1);
                            timeSet.add(Calendar.MONTH, 1);
                            timeSet.add(Calendar.DAY_OF_YEAR, -1);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            // set first day of month
                            timeSet.set(Calendar.DAY_OF_MONTH, 1);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        } else if (YEARLY.equalsIgnoreCase(timeResolution)) {
                            // Compute last day of month
                            timeSet.set(Calendar.DATE, 31);
                            timeSet.add(Calendar.MONTH, Calendar.DECEMBER);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            timeSet.set(Calendar.DATE, 1);
                            timeSet.add(Calendar.MONTH, Calendar.JANUARY);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        }
                    } else {
                        // compute end date for individual data points based on the selected resolution
                        //                     detailsPointEndDate = computeEndDate(tdates[i],timeResolution);
                        // add the date field with start and end dates from the data point
                        tmp.append(",").append(dateFieldName).append("_start:'").append(tdates[i].getTime())
                                .append("'");
                        tmp.append(",").append(dateFieldName).append("_end:'").append(tdates[i].getTime())
                                .append("'");
                    }
                    tmp.append("});");
                    urls[i] = tmp.toString();
                }

                allCounts[aIndex] = counts;
                allColors[aIndex] = colors;
                allAltTexts[aIndex] = altTexts;
                allExpecteds[aIndex] = expecteds;
                allLevels[aIndex] = levels;
                allLineSetURLs[aIndex] = urls;
                allSwitchInfo[aIndex] = switchInfo;
                lineSetLabels[aIndex] = accumIdTranslated;
                displayAlerts[aIndex] = isDetectionDetector;
                aIndex++;

                //remove the accumId for the next series
                dimIds.remove(accumId);
            }

            GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
            GraphController gc = getGraphController(null, hndl, userPrincipalName);
            //TODO figure out why I (hodancj1) added this to be accumulation size ~Feb 2012
            // gc.setMaxLegendItems(accumulations.size());

            graphData.setShowSingleAlertLegends(isDetectionDetector);
            graphData.setCounts(allCounts);
            graphData.setColors(allColors);
            graphData.setAltTexts(allAltTexts);
            graphData.setXLabels(dates);
            graphData.setExpecteds(allExpecteds);
            graphData.setLevels(allLevels);
            graphData.setLineSetURLs(allLineSetURLs);
            graphData.setLineSetLabels(lineSetLabels);
            graphData.setDisplayAlerts(displayAlerts);
            // graphData.setDisplaySeverityAlerts(displayAlerts);
            graphData.setPercentBased(percentBased);

            graphData.setXAxisLabel(messageSource.getDataSourceMessage(group.getResolution(), dss));
            graphData.setYAxisLabel(yAxisLabel);

            int maxLabels = graphData.getGraphWidth() / 30;
            graphData.setMaxLabeledCategoryTicks(Math.min(maxLabels, allCounts[0].length));

            StringBuffer sb = new StringBuffer();
            GraphObject graph = gc.writeTimeSeriesGraph(sb, graphData, true, true, false, graphTimeSeriesUrl);

            result.put("html", sb.toString());

            //added to build method calls from javascript
            Map<String, Object> graphConfig = new HashMap<String, Object>();
            graphConfig.put("address", graphTimeSeriesUrl);
            graphConfig.put("graphDataId", graph.getGraphDataId());
            graphConfig.put("imageMapName", graph.getImageMapName());

            graphConfig.put("graphTitle", graphData.getGraphTitle());
            graphConfig.put("xAxisLabel", graphData.getXAxisLabel());
            graphConfig.put("yAxisLabel", graphData.getYAxisLabel());
            graphConfig.put("xLabels", graphData.getXLabels());
            graphConfig.put("graphWidth", graphData.getGraphWidth());
            graphConfig.put("graphHeight", graphData.getGraphHeight());

            graphConfig.put("yAxisMin", graph.getYAxisMin());
            graphConfig.put("yAxisMax", graph.getYAxisMax());

            // fix invalid JSON coming from GraphController
            String dataSeriesJson = graph.getDataSeriesJSON().replaceFirst("\\{", "")
                    // remove trailing "}"
                    .substring(0, graph.getDataSeriesJSON().length() - 2);

            // read malformed JSON
            ObjectMapper mapper = new ObjectMapper();
            JsonFactory jsonFactory = mapper.getJsonFactory()
                    .configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
                    .configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            JsonParser jsonParser = jsonFactory.createJsonParser(dataSeriesJson);

            // array of String -> Object maps
            TypeReference<Map<String, Object>[]> dataSeriesType = new TypeReference<Map<String, Object>[]>() {
            };

            // write JSON as Map so that it can be serialized properly back to JSON
            Map<String, Object>[] seriesMap = mapper.readValue(jsonParser, dataSeriesType);
            graphConfig.put("dataSeriesJSON", seriesMap);

            if (includeDetails) {
                int totalPoints = 0;
                List<HashMap<String, Object>> details = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> detail;
                for (int i = 0; i < allCounts.length; i++) {
                    for (int j = 0; j < allCounts[i].length; j++) {
                        totalPoints++;
                        detail = new HashMap<String, Object>();
                        detail.put("Date", dates[j]);
                        detail.put("Series", lineSetLabels[i]);
                        detail.put("Level", allLevels[i][j]);
                        detail.put("Count", allCounts[i][j]);
                        if (!ArrayUtils.isEmpty(allExpecteds[i])) {
                            detail.put("Expected", allExpecteds[i][j]);
                        }
                        if (!ArrayUtils.isEmpty(allSwitchInfo[i])) {
                            detail.put("Switch", allSwitchInfo[i][j]);
                        }
                        detail.put("Color", allColors[i][j]);
                        details.add(detail);
                    }
                }
                result.put("detailsTotalRows", totalPoints);
                result.put("details", details);
            }
            result.put("graphConfiguration", graphConfig);
            result.put("success", true);
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("<h2>" + messageSource.getDataSourceMessage("graph.nodataline1", dss) + "</h2>");
            sb.append("<p>" + messageSource.getDataSourceMessage("graph.nodataline2", dss) + "</p>");
            result.put("html", sb.toString());
            result.put("success", true);
        }
    } catch (Exception e) {
        log.error("Failure to create Timeseries", e);
    }
    return result;
}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiToHTMLUtils.java

public static String toHtmlFormField(CustomFormField field, WikiToHTMLContext context) {
    // Set a default value
    if (field.getValue() == null) {
        field.setValue(field.getDefaultValue());
    }/*  www.ja v  a  2  s. c om*/
    // Protect against any arbitrary input
    String fieldName = StringUtils.toHtmlValue(field.getName());
    // Return output based on type
    switch (field.getType()) {
    case CustomFormField.TEXTAREA:
        String textAreaValue = StringUtils.replace(field.getValue(), "^", CRLF);
        return ("<textarea cols=\"" + field.getColumns() + "\" rows=\"" + field.getRows() + "\" name=\""
                + fieldName + "\">" + StringUtils.toString(textAreaValue) + "</textarea>");
    case CustomFormField.SELECT:
        LookupList lookupList = field.getLookupList();
        int selectedItemId = -1;
        for (LookupElement thisElement : lookupList) {
            if (field.getValue().equals(thisElement.getDescription())) {
                selectedItemId = thisElement.getCode();
            }
        }
        return lookupList.getHtmlSelect(fieldName, selectedItemId);
    case CustomFormField.CHECKBOX:
        return ("<input type=\"checkbox\" name=\"" + fieldName + "\" value=\"ON\" "
                + ("true".equals(field.getValue()) ? "checked" : "") + ">");
    case CustomFormField.CALENDAR:
        String calendarValue = field.getValue();
        if (StringUtils.hasText(calendarValue)) {
            try {
                String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT,
                        DateFormat.LONG, field.getValue());
                Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate);
                Locale locale = Locale.getDefault();
                int dateFormat = DateFormat.SHORT;
                SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat,
                        locale);
                calendarValue = dateFormatter.format(timestamp);
            } catch (Exception e) {
                LOG.error("toHtmlFormField calendar", e);
            }
        }
        // Output with a calendar control
        String language = System.getProperty("LANGUAGE");
        String country = System.getProperty("COUNTRY");
        return ("<input type=\"text\" name=\"" + fieldName + "\" id=\"" + fieldName + "\" size=\"10\" value=\""
                + StringUtils.toHtmlValue(calendarValue) + "\" > "
                + "<a href=\"javascript:popCalendar('inputForm', '" + fieldName + "','" + language + "','"
                + country + "');\">" + "<img src=\"" + context.getServerUrl()
                + "/images/icons/stock_form-date-field-16.gif\" "
                + "border=\"0\" align=\"absmiddle\" height=\"16\" width=\"16\"/></a>");
    case CustomFormField.PERCENT:
        return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"5\" value=\""
                + StringUtils.toHtmlValue(field.getValue()) + "\"> " + "%");
    case CustomFormField.INTEGER:
        // Determine the value to display in the field
        String integerValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(integerValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not format integer: " + field.getValue());
            }
        }
        return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"8\" value=\"" + integerValue + "\"> ");
    case CustomFormField.FLOAT:
        // Determine the value to display in the field
        String decimalValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(decimalValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not decimal format: " + field.getValue());
            }
        }
        return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"8\" value=\"" + decimalValue + "\"> ");
    case CustomFormField.CURRENCY:
        // Use a currencyCode for formatting
        String currencyCode = field.getValueCurrency();
        if (currencyCode == null) {
            currencyCode = field.getCurrency();
        }
        if (!StringUtils.hasText(currencyCode)) {
            currencyCode = "USD";
        }
        HtmlSelect currencyCodeList = HtmlSelectCurrencyCode.getSelect(fieldName + "Currency", currencyCode);
        // Determine the valut to display in the field
        String currencyValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(currencyValue)) {
            try {
                NumberFormat formatter = NumberFormat.getNumberInstance();
                formatter.setMaximumFractionDigits(2);
                currencyValue = formatter.format(StringUtils.getDoubleNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not currencyCode format: " + field.getValue());
            }
        }
        return (currencyCodeList.getHtml() + "<input type=\"text\" name=\"" + fieldName
                + "\" size=\"8\" value=\"" + currencyValue + "\"> ");
    case CustomFormField.EMAIL:
        return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"255\" size=\"40\" value=\""
                + StringUtils.toHtmlValue(field.getValue()) + "\" />");
    case CustomFormField.PHONE:
        return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"60\" size=\"20\" value=\""
                + StringUtils.toHtmlValue(field.getValue()) + "\" />");
    case CustomFormField.URL:
        String value = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(value)) {
            if (!value.contains("://")) {
                value = "http://" + field.getValue();
            }
        }
        return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"255\" size=\"40\" value=\""
                + StringUtils.toHtmlValue(value) + "\" />");
    default:
        int maxlength = field.getMaxLength();
        int size = -1;
        if (maxlength > -1) {
            if (maxlength > 40) {
                size = 40;
            } else {
                size = maxlength;
            }
        }
        return ("<input type=\"text\" " + "name=\"" + fieldName + "\" "
                + (maxlength == -1 ? "" : "maxlength=\"" + maxlength + "\" ")
                + (size == -1 ? "" : "size=\"" + size + "\" ") + "value=\""
                + StringUtils.toHtmlValue(field.getValue()) + "\" />");
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchFarmManager.java

private void showOverallStatus() {
    int farmCount = 0;
    int attacks = 0;
    int hauledWood = 0;
    int hauledClay = 0;
    int hauledIron = 0;
    int woodPerHour = 0;
    int clayPerHour = 0;
    int ironPerHour = 0;

    for (ManageableType type : FarmManager.getSingleton().getAllElements()) {
        FarmInformation info = (FarmInformation) type;
        attacks += info.getAttackCount();
        hauledWood += info.getHauledWood();
        hauledClay += info.getHauledClay();
        hauledIron += info.getHauledIron();
        woodPerHour += BuildingSettings.calculateResourcesPerHour(info.getWoodLevel());
        clayPerHour += BuildingSettings.calculateResourcesPerHour(info.getClayLevel());
        ironPerHour += BuildingSettings.calculateResourcesPerHour(info.getIronLevel());
        farmCount++;/*w  w w  .j a  va  2s .c o  m*/
    }

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(0);
    int overall = hauledWood + hauledClay + hauledIron;
    StringBuilder b = new StringBuilder();
    b.append("<html>");
    b.append(nf.format(farmCount));
    b.append(" Farmen<br>");
    b.append("Resourcenproduktion pro Stunde (Summe)<br>");
    b.append("<ul>");
    b.append("<li>");
    b.append("Holz: ").append(nf.format(woodPerHour)).append("</li>");
    b.append("<li>");
    b.append("Lehm: ").append(nf.format(clayPerHour)).append("</li>");
    b.append("<li>");
    b.append("Eisen: ").append(nf.format(ironPerHour)).append("</li>");
    b.append("</ul>");
    b.append(nf.format(attacks));
    b.append(" durchgef&uuml;hrte Angriffe<br>");
    b.append(nf.format(hauledWood + hauledClay + hauledIron));
    b.append(" gepl&uuml;nderte Rohstoffe (&#216; ").append(nf.format(overall / attacks)).append(")<br>");
    b.append("<ul>");
    b.append("<li>");
    b.append(nf.format(hauledWood));
    b.append(" Holz (&#216; ").append(nf.format(hauledWood / attacks)).append(")</li>");
    b.append("<li>");
    b.append(nf.format(hauledClay));
    b.append(" Lehm (&#216; ").append(nf.format(hauledClay / attacks)).append(")</li>");
    b.append("<li>");
    b.append(nf.format(hauledIron));
    b.append(" Eisen (&#216; ").append(nf.format(hauledIron / attacks)).append(")</li>");
    b.append("</ul></html>");
    JOptionPaneHelper.showInformationBox(this, b.toString(), "Status");
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

private String getFolio(Empresa empresa) {
    Query query = currentSession().createQuery(
            "select f from FolioActivo f where f.nombre = :nombre and f.organizacion.id = :organizacionId");
    query.setString("nombre", "ACTIVOS");
    query.setLong("organizacionId", empresa.getOrganizacion().getId());
    query.setLockOptions(LockOptions.UPGRADE);
    FolioActivo folio = (FolioActivo) query.uniqueResult();
    if (folio == null) {
        folio = new FolioActivo("ACTIVOS");
        folio.setOrganizacion(empresa.getOrganizacion());
        currentSession().save(folio);//from  ww w  .j  av  a2s.c  o  m
        return getFolio(empresa);
    }
    folio.setValor(folio.getValor() + 1);
    java.text.NumberFormat nf = java.text.DecimalFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMinimumIntegerDigits(7);
    nf.setMaximumIntegerDigits(7);
    nf.setMaximumFractionDigits(0);
    StringBuilder sb = new StringBuilder();
    sb.append("A-");
    sb.append(empresa.getOrganizacion().getCodigo());
    sb.append(empresa.getCodigo());
    sb.append(nf.format(folio.getValor()));
    return sb.toString();
}