Example usage for java.util Calendar DAY_OF_YEAR

List of usage examples for java.util Calendar DAY_OF_YEAR

Introduction

In this page you can find the example usage for java.util Calendar DAY_OF_YEAR.

Prototype

int DAY_OF_YEAR

To view the source code for java.util Calendar DAY_OF_YEAR.

Click Source Link

Document

Field number for get and set indicating the day number within the current year.

Usage

From source file:com.netflix.genie.web.tasks.job.JobMonitorUnitTests.java

/**
 * Make sure that a timed out process sends event.
 *
 * @throws IOException on error/*from  www  . ja  va2s . c  o  m*/
 */
@Test
public void canTryToKillTimedOutProcess() throws IOException {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);

    // Set timeout to yesterday to force timeout when check happens
    final Calendar yesterday = Calendar.getInstance(JobConstants.UTC);
    yesterday.add(Calendar.DAY_OF_YEAR, -1);
    this.jobExecution = new JobExecution.Builder(UUID.randomUUID().toString()).withProcessId(3808)
            .withCheckDelay(DELAY).withTimeout(yesterday.getTime()).withId(UUID.randomUUID().toString())
            .build();
    this.monitor = new JobMonitor(this.jobExecution, this.stdOut, this.stdErr, this.executor, this.publisher,
            this.eventMulticaster, this.registry, new JobsProperties());

    this.monitor.run();

    final ArgumentCaptor<KillJobEvent> captor = ArgumentCaptor.forClass(KillJobEvent.class);
    Mockito.verify(this.publisher, Mockito.times(1)).publishEvent(captor.capture());

    Assert.assertNotNull(captor.getValue());
    final String jobId = this.jobExecution.getId().orElseThrow(IllegalArgumentException::new);
    Assert.assertThat(captor.getValue().getId(), Matchers.is(jobId));
    Assert.assertThat(captor.getValue().getReason(), Matchers.is("Job exceeded timeout"));
    Assert.assertThat(captor.getValue().getSource(), Matchers.is(this.monitor));
    Mockito.verify(this.timeoutRate, Mockito.times(1)).increment();
}

From source file:com.virtusa.akura.student.delegate.StudentLoginDelegate.java

/**
 * method to calculate attendance average.
 * //  w ww.  j av a2 s  .c  o  m
 * @param studentId - integer
 * @return average in double. * @param year - Date
 * @throws AkuraAppException when exception occurs
 * @return attendance average in double.
 */
private double calculateAttendance(int studentId, Date year) throws AkuraAppException {

    Student student = studentService.findStudent(studentId);

    String strStartDate = "";

    String strEndDate = DateUtil.getStringYear(year) + END_YEAR;

    Calendar firstDayCalendar = Calendar.getInstance();
    firstDayCalendar.setTime(student.getFirstSchoolDay());
    String firstDayYear = Integer.toString(firstDayCalendar.get(Calendar.YEAR));
    boolean checkFirstday = false;

    if (firstDayYear.equals(DateUtil.getStringYear(year))) {
        strStartDate = DateUtil.getFormatDate(student.getFirstSchoolDay());
        checkFirstday = true;
    } else {
        strStartDate = DateUtil.getStringYear(year) + START_YEAR;
    }

    List<Holiday> holidayList = commonService.findHolidayByYear(DateUtil.getParseDate(strStartDate),
            DateUtil.getParseDate(strEndDate));
    Calendar calendar = Calendar.getInstance();
    Date dateTo = calendar.getTime();
    dateTo = DateUtil.getParseDate(DateUtil.getFormatDate(dateTo));
    Date dateFrom = DateUtil.getParseDate(strStartDate);
    dateFrom = DateUtil.getParseDate(DateUtil.getFormatDate(dateFrom));
    Calendar fromDate = Calendar.getInstance();
    fromDate.setTime(dateFrom);

    Calendar toDate = Calendar.getInstance();
    toDate.setTime(dateTo);
    int holidayCount = HolidayUtil.countHolidays(fromDate, toDate, holidayList);
    fromDate.setTime(dateFrom);
    int numberOfDays = 0;

    if (checkFirstday) {
        if (!fromDate.after(toDate)) {
            int dayCount = toDate.get(Calendar.DAY_OF_YEAR) - fromDate.get(Calendar.DAY_OF_YEAR);
            numberOfDays = dayCount - holidayCount;
        }

    } else {

        numberOfDays = calendar.get(Calendar.DAY_OF_YEAR) - holidayCount;
    }

    numberOfDays++;
    int numbeeOfPresentDays = dailyAttendanceService.getAttendanceBettween(studentId, dateFrom, dateTo).size();

    double presentDays = (double) numbeeOfPresentDays / numberOfDays;

    return presentDays * HUNDRED;

}

From source file:com.application.utils.FastDatePrinter.java

/**
 * <p>Returns a list of Rules given a pattern.</p>
 *
 * @return a {@code List} of Rule objects
 * @throws IllegalArgumentException if pattern is invalid
 *///from ww w  .j  a  v a2s.  c o  m
protected List<Rule> parsePattern() {
    final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
    final List<Rule> rules = new ArrayList<Rule>();

    final String[] ERAs = symbols.getEras();
    final String[] months = symbols.getMonths();
    final String[] shortMonths = symbols.getShortMonths();
    final String[] weekdays = symbols.getWeekdays();
    final String[] shortWeekdays = symbols.getShortWeekdays();
    final String[] AmPmStrings = symbols.getAmPmStrings();

    final int length = mPattern.length();
    final int[] indexRef = new int[1];

    for (int i = 0; i < length; i++) {
        indexRef[0] = i;
        final String token = parseToken(mPattern, indexRef);
        i = indexRef[0];

        final int tokenLen = token.length();
        if (tokenLen == 0) {
            break;
        }

        Rule rule;
        final char c = token.charAt(0);

        switch (c) {
        case 'G': // era designator (text)
            rule = new TextField(Calendar.ERA, ERAs);
            break;
        case 'y': // year (number)
            if (tokenLen == 2) {
                rule = TwoDigitYearField.INSTANCE;
            } else {
                rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
            }
            break;
        case 'M': // month in year (text and number)
            if (tokenLen >= 4) {
                rule = new TextField(Calendar.MONTH, months);
            } else if (tokenLen == 3) {
                rule = new TextField(Calendar.MONTH, shortMonths);
            } else if (tokenLen == 2) {
                rule = TwoDigitMonthField.INSTANCE;
            } else {
                rule = UnpaddedMonthField.INSTANCE;
            }
            break;
        case 'd': // day in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
            break;
        case 'h': // hour in am/pm (number, 1..12)
            rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
            break;
        case 'H': // hour in day (number, 0..23)
            rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
            break;
        case 'm': // minute in hour (number)
            rule = selectNumberRule(Calendar.MINUTE, tokenLen);
            break;
        case 's': // second in minute (number)
            rule = selectNumberRule(Calendar.SECOND, tokenLen);
            break;
        case 'S': // millisecond (number)
            rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
            break;
        case 'E': // day in week (text)
            rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
            break;
        case 'D': // day in year (number)
            rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
            break;
        case 'F': // day of week in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
            break;
        case 'w': // week in year (number)
            rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
            break;
        case 'W': // week in month (number)
            rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
            break;
        case 'a': // am/pm marker (text)
            rule = new TextField(Calendar.AM_PM, AmPmStrings);
            break;
        case 'k': // hour in day (1..24)
            rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
            break;
        case 'K': // hour in am/pm (0..11)
            rule = selectNumberRule(Calendar.HOUR, tokenLen);
            break;
        case 'z': // time zone (text)
            if (tokenLen >= 4) {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
            } else {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
            }
            break;
        case 'Z': // time zone (value)
            if (tokenLen == 1) {
                rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
            } else {
                rule = TimeZoneNumberRule.INSTANCE_COLON;
            }
            break;
        case '\'': // literal text
            final String sub = token.substring(1);
            if (sub.length() == 1) {
                rule = new CharacterLiteral(sub.charAt(0));
            } else {
                rule = new StringLiteral(sub);
            }
            break;
        default:
            throw new IllegalArgumentException("Illegal pattern component: " + token);
        }

        rules.add(rule);
    }

    return rules;
}

From source file:GenAppStoreSales.java

private static void readSales(String periodTime, boolean restoreSales, boolean computeSales)
        throws IOException {
    countryLabels = new ArrayList<String>();
    countryUnits = new ArrayList<ArrayList<Integer>>();
    countryInAppLabels = new ArrayList<String>();
    countryInAppUnits = new ArrayList<ArrayList<Integer>>();
    int t = 0, periodDays = 0;
    boolean anotherDay = true;
    if (periodTime.equals("day"))
        periodDays = 1;//from  w  w  w .  j  a v  a 2 s  .c o m
    else if (periodTime.equals("week"))
        periodDays = 7;
    else if (periodTime.equals("month"))
        periodDays = rollCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    else if (periodTime.equals("year"))
        periodDays = rollCalendar.getActualMaximum(Calendar.DAY_OF_YEAR);
    else if (periodTime.equals("custom")) {
        while (rollCalendar.compareTo(customCalendar) > 0) {
            rollCalendar.add(Calendar.DATE, -1);
            periodDays++;
        }
        rollCalendar.add(Calendar.DATE, periodDays);
    }

    while (anotherDay) {
        String dateCode = String.format("%d%02d%02d", pursuedYear, pursuedMonth, pursuedDay);
        String reportName = "S_D_" + appID + "_" + dateCode + ".txt";
        File salesFile = new File(sourcePath + "/" + reportName);
        if (salesFile.isFile()) {
            String SKU, productCountry;
            int productUnits;
            boolean update;
            float productPrice;
            BufferedReader salesFileReader = new BufferedReader(new FileReader(sourcePath + "/" + reportName));
            String line = salesFileReader.readLine(); // skips the first line
            while ((line = salesFileReader.readLine()) != null) {
                String[] columns = line.split("\t");
                // SKU
                SKU = columns[2];
                // Product Units
                if (columns[6].equals("7T"))
                    update = true;
                else
                    update = false;
                productUnits = Integer.parseInt(columns[7]);
                // Product Price
                productPrice = Float.parseFloat(columns[8]);
                // Country Code
                productCountry = columns[12];

                //                 System.out.println("SKU " + SKU + " Units " + productUnits + " Country Code " + productCountry);

                if (SKU.equals(appSKU)) {
                    if (periodTime.equals("day")) {
                        dayUnits += productUnits;
                    }
                    if (computeSales) {
                        totalUnits += productUnits;
                        if (update) {
                            totalUpdateUnits += productUnits;
                        }
                    }
                    if (restoreSales) {
                        int index = countryLabels.indexOf(productCountry);
                        if (index < 0) {
                            countryLabels.add(productCountry);
                            countryUnits.add(new ArrayList<Integer>(Collections.nCopies(periodDays, 0)));
                            countryUnits.get(countryUnits.size() - 1).set(t, productUnits);
                        } else
                            countryUnits.get(index).set(t, productUnits);
                    }
                } else {
                    if (periodTime.equals("day")) {
                        dayINAPPUnits += productUnits;
                    }
                    if (computeSales) {
                        totalInAppUnits += productUnits;
                    }
                    if (restoreSales) {
                        int index = countryInAppLabels.indexOf(productCountry);
                        if (index < 0) {
                            countryInAppLabels.add(productCountry);
                            countryInAppUnits.add(new ArrayList<Integer>(Collections.nCopies(periodDays, 0)));
                            countryInAppUnits.get(countryInAppUnits.size() - 1).set(t, productUnits);
                        } else
                            countryInAppUnits.get(index).set(t, productUnits);
                    }
                }
            }
            salesFileReader.close();
        }

        if (periodTime.equals("day")) {
            anotherDay = false;
        } else if (periodTime.equals("week")) {
            if (rollCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
                anotherDay = false;
            }
        } else if (periodTime.equals("month")) {
            if (rollCalendar.get(Calendar.DAY_OF_MONTH) == 1) {
                anotherDay = false;
            }
        } else if (periodTime.equals("year")) {
            if (rollCalendar.get(Calendar.DAY_OF_YEAR) == 1) {
                anotherDay = false;
            }
        } else if (periodTime.equals("custom")) {
            if (rollCalendar.compareTo(customCalendar) <= 0) {
                anotherDay = false;
            }
        }
        rollCalendar.add(Calendar.DATE, -1);
        updateRollCalendar();
        t++;
    }
}

From source file:com.fengduo.bee.commons.util.DateViewTools.java

public static String yesterdayFull() {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, -1);
    return getFormat(FULL_DATE_FORMAT_PATTERN).format(yesterDate());
}

From source file:com.example.app.profile.ui.user.UserPropertyEditor.java

@SuppressWarnings("Duplicates")
@Override//from   www . j av a 2  s.c o m
public void init() {
    super.init();

    NavigationAction saveAction = CommonActions.SAVE.navAction();
    saveAction.onCondition(input -> persist(user -> {
        assert user != null : "User should not be null if you are persisting!";
        UserValueEditor editor = getValueEditor();
        User currentUser = _userDAO.getAssertedCurrentUser();
        _sessionHelper.beginTransaction();
        boolean success = false;
        try {
            if (Objects.equals(currentUser.getId(), user.getId())) {
                user.setPreferredContactMethod(editor.commitValuePreferredContactMethod());

                final Link link = editor.commitValueLoginLandingPage();
                if (link != null) {
                    Preferences userPref = Preferences.userRoot().node(User.LOGIN_PREF_NODE);
                    userPref.put(User.LOGIN_PREF_NODE_LANDING_PAGE, link.getURIAsString());
                }
            }

            user = _userDAO.mergeUser(user);
            try {
                boolean result = true;
                EmailAddress emailAddress = ContactUtil
                        .getEmailAddress(user.getPrincipal().getContact(), ContactDataCategory.values())
                        .orElseThrow(() -> new IllegalStateException(
                                "Email Address was null on PrincipalValueEditor.  This should not happen."));
                if (user.getPrincipal().getPasswordCredentials() == null) {
                    String randomPassword = UUID.randomUUID().toString();

                    List<Notification> notifications = new ArrayList<>();

                    result = _principalDAO.setNewPassword(user.getPrincipal(), emailAddress.getEmail(),
                            notifications, randomPassword);

                    if (result) {
                        user.setPrincipal(_er.reattachIfNecessary(user.getPrincipal()));

                        user.getPrincipal().getCredentials().forEach(cred -> {
                            if (_er.narrowProxyIfPossible(cred) instanceof PasswordCredentials) {
                                Calendar cal = Calendar.getInstance();
                                cal.add(Calendar.DAY_OF_YEAR, -10);
                                cred.setExpireDate(cal.getTime());
                            }
                        });

                        _principalDAO.savePrincipal(user.getPrincipal());
                    } else {
                        final Notifiable notifiable = getNotifiable();
                        notifications.forEach(notifiable::sendNotification);
                    }
                } else {
                    PasswordCredentials creds = user.getPrincipal().getPasswordCredentials();
                    creds.setUsername(emailAddress.getEmail());
                    _principalDAO.savePrincipal(user.getPrincipal());
                }
                if (!_principalDAO.getAllRoles(user.getPrincipal())
                        .contains(_appUtil.getFrontEndAccessRole())) {
                    user.getPrincipal().getChildren().add(_appUtil.getFrontEndAccessRole());
                    _principalDAO.savePrincipal(user.getPrincipal());
                }
                user = _userDAO.mergeUser(user);
                Company userProfile = _uiPreferences.getSelectedCompany();
                if (userProfile != null && !userProfile.getUsers().contains(user) && _newUser) {
                    _companyDAO.addUserToCompany(userProfile, user);

                    List<MembershipType> coachingMemTypes = editor.commitValueCoachingMemType();
                    final User finalUser = user;
                    coachingMemTypes.forEach(coachingMemType -> _profileDAO.saveMembership(
                            _profileDAO.createMembership(userProfile, finalUser, coachingMemType,
                                    ZonedDateTime.now(getSession().getTimeZone().toZoneId()), true)));
                }

                if (editor.getPictureEditor().getModificationState().isModified()) {
                    _userDAO.saveUserImage(user, editor.getPictureEditor().commitValue());
                }

                success = result;
                if (success) {
                    setSaved(user);
                }
            } catch (NonUniqueCredentialsException e) {
                _logger.error("Unable to persist changes to the Principal.", e);
                getNotifiable().sendNotification(error(ERROR_MESSAGE_USERNAME_EXISTS_FMT(USER())));
            }
            _sessionHelper.commitTransaction();
        } finally {
            if (!success)
                _sessionHelper.recoverableRollbackTransaction();
        }
        if (success) {
            _uiPreferences.addMessage(
                    new NotificationImpl(NotificationType.INFO, INFO_SHOULD_PICK_ONE_ROLE_NEW_USER()));
        }
        return success;
    }));
    saveAction.configure().toPage(ApplicationFunctions.User.VIEW).withSourceComponent(this);
    saveAction.setPropertyValueResolver(new CurrentURLPropertyValueResolver() {
        @Override
        public Map<String, Object> resolve(PropertyValueResolverParameter parameter) {
            Map<String, Object> map = super.resolve(parameter);
            map.put(URLProperties.USER, _saved);
            return map;
        }
    });
    saveAction.setTarget(this, "close");

    NavigationAction cancelAction = CommonActions.CANCEL.navAction();
    cancelAction.configure().toReturnPath(ApplicationFunctions.User.MANAGEMENT).usingCurrentURLData()
            .withSourceComponent(this);
    cancelAction.setTarget(this, "close");

    setPersistenceActions(saveAction, cancelAction);

    _notifications.forEach(notification -> getNotifiable().sendNotification(notification));
}

From source file:com.appeligo.search.actions.SearchResults.java

private Query generateLuceneQuery(String givenQuery, IndexSearcher searcher) throws ParseException {
    if (givenQuery == null) {
        givenQuery = getQuery();/*from  w w  w. j a  v a 2  s  .co  m*/
    }
    HashMap<String, Float> boost = new HashMap<String, Float>();
    boost.put("programTitle", 8.0f);
    boost.put("episodeTitle", 3.0f);
    boost.put("description", 2.0f);
    MultiFieldQueryParser parser = new MultiFieldQueryParser(
            new String[] { "text", "description", "programTitle", "episodeTitle", "credits", "genre" },
            analyzer, boost);
    parser.setDefaultOperator(Operator.AND);

    Query luceneQuery = null;
    try {
        luceneQuery = parser.parse(givenQuery);
    } catch (ParseException e) {
        log.error("Error parsing query for : " + givenQuery);
        if (log.isDebugEnabled()) {
            log.debug("Error parsing query for : " + givenQuery, e);
        }
        givenQuery = QueryParser.escape(givenQuery);
        luceneQuery = parser.parse(givenQuery);
    }
    BooleanQuery combinedQuery = new BooleanQuery();
    combinedQuery.add(luceneQuery, Occur.MUST);

    //This will move into a setting on the user.
    Query tvma = new TermQuery(new Term("tvRating", "TVMA"));
    combinedQuery.add(tvma, Occur.MUST_NOT);

    if (lineup != null) {
        //Only find programs that were on networks that are in the lineup
        TermQuery lineupQuery = new TermQuery(new Term("lineup-" + lineup, "true"));
        combinedQuery.add(lineupQuery, Occur.MUST);
    }

    if (searchType != null) {
        if (lineup == null) {
            throw new ParseException(
                    "Lineup cannot be null if searching based on date.  searchType=" + searchType);
        }
        switch (searchType) {
        case FUTURE: {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, 14);
            Date future = cal.getTime();
            Date now = new Date();
            ConstantScoreRangeQuery dateQuery = new ConstantScoreRangeQuery("lineup-" + lineup + "-endTime",
                    DateTools.dateToString(now, DateTools.Resolution.MINUTE),
                    DateTools.dateToString(future, DateTools.Resolution.MINUTE), true, true);
            combinedQuery.add(dateQuery, Occur.MUST);
            break;
        }
        case TODAY: {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
            cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
            Date future = cal.getTime();
            Date now = new Date();
            ConstantScoreRangeQuery dateQuery = new ConstantScoreRangeQuery("lineup-" + lineup + "-endTime",
                    DateTools.dateToString(now, DateTools.Resolution.MINUTE),
                    DateTools.dateToString(future, DateTools.Resolution.MINUTE), true, true);
            combinedQuery.add(dateQuery, Occur.MUST);
            break;
        }
        }
    }
    if (modifiedSince != null) {
        Date now = new Date();
        ConstantScoreRangeQuery dateQuery = new ConstantScoreRangeQuery("lastModified",
                DateTools.dateToString(modifiedSince, DateTools.Resolution.MINUTE),
                DateTools.dateToString(now, DateTools.Resolution.MINUTE), true, true);
        combinedQuery.add(dateQuery, Occur.MUST);
    }
    return combinedQuery;
}

From source file:at.diamonddogs.util.Utils.java

/**
 * Converts input values to a {@link Calendar}
 *
 * @param dayOfWeek/*ww  w.  j  av  a 2s.  c o m*/
 * @param hourOfDay
 * @param minute
 * @param second
 * @return a {@link Calendar}r with the provided date
 */
public static final Calendar getScheduledDate(int dayOfWeek, int hourOfDay, int minute, int second) {
    Calendar c = Calendar.getInstance();
    int weekDay = c.get(Calendar.DAY_OF_WEEK);
    int days = dayOfWeek - weekDay;
    if (days < 0) {
        days += 7;
    }
    c.add(Calendar.DAY_OF_YEAR, days);
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, second);
    return c;
}

From source file:asl.util.PlotMaker.java

public void plotPSD(double per[], double[] model, double[] nhnmPer, double[] nhnm, double[] psd,
        String modelName, String plotString) {

    // plotTitle = "2012074.IU_ANMO.00-BHZ " + plotString
    final String plotTitle = String.format("%04d%03d.%s.%s %s", date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channel, plotString);
    // plot filename = "2012074.IU_ANMO.00-BHZ" + plotString + ".png"
    final String pngName = String.format("%s/%04d%03d.%s.%s.%s.png", outputDir, date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channel, plotString);
    File outputFile = new File(pngName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format(//from   w  ww  .j  a v a2  s.  com
                "== plotPSD: request to output plot=[%s] but we are unable to create it " + " --> skip plot\n",
                pngName);
        return;
    }

    Boolean plotNHNM = false;
    //if (nhnm.length > 0) {
    if (nhnm != null) {
        plotNHNM = true;
    }

    final XYSeries series1 = new XYSeries(modelName);
    final XYSeries series2 = new XYSeries(channel.toString());
    final XYSeries series3 = new XYSeries("NHNM");

    for (int k = 0; k < per.length; k++) {
        series1.add(per[k], model[k]);
        series2.add(per[k], psd[k]);
    }

    if (plotNHNM) {
        for (int k = 0; k < nhnmPer.length; k++) {
            series3.add(nhnmPer[k], nhnm[k]);
        }
    }

    //final XYItemRenderer renderer = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);

    renderer.setSeriesShape(0, rectangle);
    renderer.setSeriesShapesVisible(0, false);
    renderer.setSeriesLinesVisible(0, true);

    renderer.setSeriesShape(1, rectangle);
    renderer.setSeriesShapesVisible(1, true);
    renderer.setSeriesLinesVisible(1, false);

    renderer.setSeriesShape(2, rectangle);
    renderer.setSeriesShapesVisible(2, false);
    renderer.setSeriesLinesVisible(2, true);

    Paint[] paints = new Paint[] { Color.blue, Color.red, Color.black };
    renderer.setSeriesPaint(0, paints[0]);
    renderer.setSeriesPaint(1, paints[1]);
    renderer.setSeriesPaint(2, paints[2]);

    final NumberAxis rangeAxis1 = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
    //rangeAxis1.setRange( new Range(-190, -120));
    rangeAxis1.setRange(new Range(-190, -95));
    rangeAxis1.setTickUnit(new NumberTickUnit(5.0));

    final LogarithmicAxis horizontalAxis = new LogarithmicAxis("Period (sec)");
    horizontalAxis.setRange(new Range(0.05, 10000));

    final XYSeriesCollection seriesCollection = new XYSeriesCollection();
    seriesCollection.addSeries(series1);
    seriesCollection.addSeries(series2);

    if (plotNHNM) {
        seriesCollection.addSeries(series3);
    }

    final XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, rangeAxis1, renderer);

    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.black);
    xyplot.setDomainGridlinePaint(Color.black);

    final JFreeChart chart = new JFreeChart(xyplot);
    chart.setTitle(new TextTitle(plotTitle));

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 500, 300);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }
}

From source file:com.mobileman.projecth.business.DoctorServiceTest.java

/**
 * /*from ww w  .j av a2  s . co m*/
 * @throws Exception
 */
@Test
public void saveManualKpiValue_WithData() throws Exception {

    Doctor doctor1 = (Doctor) userService.findUserByLogin("sysuser3");
    assertNotNull(doctor1);

    List<PatientKeyPerformanceIndicatorValidation> validations = patientKPIValidationService.findAll();
    assertNotNull(validations);
    assertEquals(0, validations.size());

    Patient patient = patientService.findAll().get(0);
    assertNotNull(patient);

    Disease disease = diseaseService.findByCode("M79.0");
    assertNotNull(disease);

    KeyPerformanceIndicatorType questionaryValidationType = keyPerformanceIndicatorTypeService.find("CDAI",
            disease.getId());

    List<BigDecimal> data = new ArrayList<BigDecimal>();
    data.add(new BigDecimal("12.3"));
    data.add(new BigDecimal("123"));

    doctorService.saveValidatedKpiValue(doctor1.getId(), patient.getId(), new Date(), questionaryValidationType,
            new BigDecimal("15"), data);

    validations = patientKPIValidationService.findAll();
    assertNotNull(validations);
    assertEquals(1, validations.size());

    Calendar calendar = new GregorianCalendar();
    calendar.add(Calendar.DAY_OF_YEAR, -1);
    Date start = calendar.getTime();
    calendar.add(Calendar.DAY_OF_YEAR, 2);
    Date end = calendar.getTime();
    List<PatientKeyPerformanceIndicatorValidation> values = patientKPIValidationService
            .findValidatedValues(patient.getId(), questionaryValidationType.getId(), start, end);
    assertEquals(1, values.size());
    assertEquals(15, values.get(0).getValue().intValue());
    assertEquals(2, values.get(0).getData().size());
    assertEquals(12.3d, values.get(0).getData().get(0).doubleValue(), 0.01);
    assertEquals(123.0d, values.get(0).getData().get(1).doubleValue(), 0.01);

    values.get(0).getData().clear();
    values.get(0).getData().add(new BigDecimal("0.70"));
    patientKPIValidationService.update(values.get(0));

    values = patientKPIValidationService.findValidatedValues(patient.getId(), questionaryValidationType.getId(),
            start, end);
    assertEquals(0.7d, values.get(0).getData().get(0).doubleValue(), 0.01);

}