Example usage for java.util Calendar getActualMaximum

List of usage examples for java.util Calendar getActualMaximum

Introduction

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

Prototype

public int getActualMaximum(int field) 

Source Link

Document

Returns the maximum value that the specified calendar field could have, given the time value of this Calendar.

Usage

From source file:com.mss.msp.util.DateUtility.java

public String CurrentMonthLastDate() throws ParseException {
    Calendar cal = Calendar.getInstance();
    int cur_year = cal.get(Calendar.YEAR);
    int cur_month = cal.get(Calendar.MONTH);
    cal.set(cur_year, cur_month, 1); //------>
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

    return sdf.format(cal.getTime());
}

From source file:net.groupbuy.controller.admin.SalesController.java

/**
 * //from  w  ww  . ja v  a 2 s .  co  m
 */
@RequestMapping(value = "/view", method = RequestMethod.GET)
public String view(Type type, Date beginDate, Date endDate, Model model) {
    if (type == null) {
        type = Type.month;
    }
    if (beginDate == null) {
        beginDate = DateUtils.addMonths(new Date(), -11);
    }
    if (endDate == null) {
        endDate = new Date();
    }
    Map<Date, BigDecimal> salesAmountMap = new LinkedHashMap<Date, BigDecimal>();
    Map<Date, Integer> salesVolumeMap = new LinkedHashMap<Date, Integer>();
    Calendar beginCalendar = DateUtils.toCalendar(beginDate);
    Calendar endCalendar = DateUtils.toCalendar(endDate);
    int beginYear = beginCalendar.get(Calendar.YEAR);
    int endYear = endCalendar.get(Calendar.YEAR);
    int beginMonth = beginCalendar.get(Calendar.MONTH);
    int endMonth = endCalendar.get(Calendar.MONTH);
    for (int year = beginYear; year <= endYear; year++) {
        if (salesAmountMap.size() >= MAX_SIZE) {
            break;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        if (type == Type.year) {
            calendar.set(Calendar.MONTH, calendar.getActualMinimum(Calendar.MONTH));
            calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE));
            calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY));
            calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE));
            calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND));
            Date begin = calendar.getTime();
            calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
            calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
            calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
            calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
            calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
            Date end = calendar.getTime();
            BigDecimal salesAmount = orderService.getSalesAmount(begin, end);
            Integer salesVolume = orderService.getSalesVolume(begin, end);
            salesAmountMap.put(begin, salesAmount != null ? salesAmount : BigDecimal.ZERO);
            salesVolumeMap.put(begin, salesVolume != null ? salesVolume : 0);
        } else {
            for (int month = year == beginYear ? beginMonth
                    : calendar.getActualMinimum(Calendar.MONTH); month <= (year == endYear ? endMonth
                            : calendar.getActualMaximum(Calendar.MONTH)); month++) {
                if (salesAmountMap.size() >= MAX_SIZE) {
                    break;
                }
                calendar.set(Calendar.MONTH, month);
                calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE));
                calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY));
                calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE));
                calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND));
                Date begin = calendar.getTime();
                calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
                calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
                calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
                calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
                Date end = calendar.getTime();
                BigDecimal salesAmount = orderService.getSalesAmount(begin, end);
                Integer salesVolume = orderService.getSalesVolume(begin, end);
                salesAmountMap.put(begin, salesAmount != null ? salesAmount : BigDecimal.ZERO);
                salesVolumeMap.put(begin, salesVolume != null ? salesVolume : 0);
            }
        }
    }
    model.addAttribute("types", Type.values());
    model.addAttribute("type", type);
    model.addAttribute("beginDate", beginDate);
    model.addAttribute("endDate", endDate);
    model.addAttribute("salesAmountMap", salesAmountMap);
    model.addAttribute("salesVolumeMap", salesVolumeMap);
    return "/admin/sales/view";
}

From source file:stepReport.model.PeriodoModel.java

private String[] calcPeriodoMes(String Mes) {
    Calendar c = Calendar.getInstance();

    String ano = Mes.substring(6, 10);
    String mes = Mes.substring(3, 5);

    mes = Integer.toString(Integer.parseInt(mes) - 1);

    c.set(Integer.parseInt(ano), Integer.parseInt(mes), 1);

    int day = c.get(Calendar.DAY_OF_WEEK);
    while (day != Calendar.SUNDAY) {
        c.add(Calendar.DAY_OF_WEEK, 1);
        day = c.get(Calendar.DAY_OF_WEEK);
    }/*from  ww w  . ja v  a2 s  .c o  m*/

    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
    String dataIni = fmt.format(c.getTime());

    int maxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
    c = Calendar.getInstance();
    c.set(Integer.parseInt(ano), Integer.parseInt(mes), maxDay);
    day = c.get(Calendar.DAY_OF_MONTH);
    while (day != Calendar.SUNDAY) {
        c.add(Calendar.DAY_OF_WEEK, 1);
        day = c.get(Calendar.DAY_OF_WEEK);
    }
    String dataFim = fmt.format(c.getTime());

    String[] v = { dataIni, dataFim };
    return v;
}

From source file:com.esofthead.mycollab.module.project.view.TimeTrackingSummaryViewImpl.java

@Override
public void display() {
    projects = ApplicationContextUtil.getSpringBean(ProjectService.class)
            .getProjectsUserInvolved(AppContext.getUsername(), AppContext.getAccountId());
    if (CollectionUtils.isNotEmpty(projects)) {
        itemTimeLoggingService = ApplicationContextUtil.getSpringBean(ItemTimeLoggingService.class);

        final CssLayout headerWrapper = new CssLayout();
        headerWrapper.setWidth("100%");
        headerWrapper.setStyleName("projectfeed-hdr-wrapper");

        HorizontalLayout loggingPanel = new HorizontalLayout();

        HorizontalLayout controlBtns = new HorizontalLayout();
        controlBtns.setMargin(new MarginInfo(true, false, true, false));

        final Label layoutHeader = new Label(
                ProjectAssetsManager.getAsset(ProjectTypeConstants.TIME).getHtml() + " Time Tracking",
                ContentMode.HTML);
        layoutHeader.addStyleName("h2");

        final MHorizontalLayout header = new MHorizontalLayout().withWidth("100%");
        header.with(layoutHeader).withAlign(layoutHeader, Alignment.MIDDLE_LEFT).expand(layoutHeader);

        final CssLayout contentWrapper = new CssLayout();
        contentWrapper.setWidth("100%");
        contentWrapper.addStyleName(UIConstants.CONTENT_WRAPPER);

        headerWrapper.addComponent(header);
        this.addComponent(headerWrapper);
        contentWrapper.addComponent(controlBtns);

        MHorizontalLayout controlsPanel = new MHorizontalLayout().withWidth("100%");

        contentWrapper.addComponent(controlsPanel);
        contentWrapper.addComponent(loggingPanel);
        this.addComponent(contentWrapper);

        final Button backBtn = new Button("Back to Workboard");
        backBtn.addClickListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            @Override/*from   w  w w .  j  a  v  a  2 s  . com*/
            public void buttonClick(final ClickEvent event) {
                EventBusFactory.getInstance()
                        .post(new ShellEvent.GotoProjectModule(TimeTrackingSummaryViewImpl.this, null));

            }
        });

        backBtn.addStyleName(UIConstants.THEME_GREEN_LINK);
        backBtn.setIcon(FontAwesome.ARROW_LEFT);

        controlBtns.addComponent(backBtn);

        VerticalLayout selectionLayoutWrapper = new VerticalLayout();
        selectionLayoutWrapper.setWidth("100%");
        selectionLayoutWrapper.addStyleName("time-tracking-summary-search-panel");
        controlsPanel.addComponent(selectionLayoutWrapper);

        final GridLayout selectionLayout = new GridLayout(9, 2);
        selectionLayout.setSpacing(true);
        selectionLayout.setDefaultComponentAlignment(Alignment.TOP_RIGHT);
        selectionLayout.setMargin(true);
        selectionLayoutWrapper.addComponent(selectionLayout);

        Label fromLb = new Label("From:");
        fromLb.setWidthUndefined();
        selectionLayout.addComponent(fromLb, 0, 0);

        this.fromDateField = new PopupDateFieldExt();
        this.fromDateField.setResolution(Resolution.DAY);
        this.fromDateField.setDateFormat(AppContext.getUserDateFormat().getDateFormat());
        this.fromDateField.setWidth("100px");
        selectionLayout.addComponent(this.fromDateField, 1, 0);

        Label toLb = new Label("To:");
        toLb.setWidthUndefined();
        selectionLayout.addComponent(toLb, 2, 0);

        this.toDateField = new PopupDateFieldExt();
        this.toDateField.setResolution(Resolution.DAY);
        this.toDateField.setDateFormat(AppContext.getUserDateFormat().getDateFormat());
        this.toDateField.setWidth("100px");
        selectionLayout.addComponent(this.toDateField, 3, 0);

        Label groupLb = new Label("Group:");
        groupLb.setWidthUndefined();
        selectionLayout.addComponent(groupLb, 0, 1);

        this.groupField = new ValueComboBox(false, GROUPBY_PROJECT, GROUPBY_DATE, GROUPBY_USER);
        this.groupField.setWidth("100px");
        selectionLayout.addComponent(this.groupField, 1, 1);

        Label sortLb = new Label("Sort:");
        sortLb.setWidthUndefined();
        selectionLayout.addComponent(sortLb, 2, 1);

        this.orderField = new ItemOrderComboBox();
        this.orderField.setWidth("100px");
        selectionLayout.addComponent(this.orderField, 3, 1);

        Label projectLb = new Label("Project:");
        projectLb.setWidthUndefined();
        selectionLayout.addComponent(projectLb, 4, 0);

        this.projectField = new UserInvolvedProjectsListSelect();
        initListSelectStyle(this.projectField);
        selectionLayout.addComponent(this.projectField, 5, 0, 5, 1);

        Label userLb = new Label("User:");
        userLb.setWidthUndefined();
        selectionLayout.addComponent(userLb, 6, 0);

        this.userField = new UserInvolvedProjectsMemberListSelect(getProjectIds());
        initListSelectStyle(this.userField);
        selectionLayout.addComponent(this.userField, 7, 0, 7, 1);

        final Button queryBtn = new Button(AppContext.getMessage(GenericI18Enum.BUTTON_SUBMIT),
                new Button.ClickListener() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public void buttonClick(final ClickEvent event) {
                        fromDate = fromDateField.getValue();
                        toDate = toDateField.getValue();
                        searchCriteria.setRangeDate(new RangeDateSearchField(fromDate, toDate));
                        searchTimeReporting();
                    }
                });
        queryBtn.setStyleName(UIConstants.THEME_GREEN_LINK);

        selectionLayout.addComponent(queryBtn, 8, 0);

        loggingPanel.setWidth("100%");
        loggingPanel.setHeight("80px");
        loggingPanel.setSpacing(true);

        totalHoursLoggingLabel = new Label("Total Hours Logging: 0 Hrs", ContentMode.HTML);
        totalHoursLoggingLabel.addStyleName(UIConstants.LAYOUT_LOG);
        totalHoursLoggingLabel.addStyleName(UIConstants.TEXT_LOG_DATE_FULL);
        loggingPanel.addComponent(totalHoursLoggingLabel);
        loggingPanel.setExpandRatio(totalHoursLoggingLabel, 1.0f);
        loggingPanel.setComponentAlignment(totalHoursLoggingLabel, Alignment.MIDDLE_LEFT);

        Button exportBtn = new Button("Export", new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                exportButtonControl.setPopupVisible(true);

            }
        });
        exportButtonControl = new SplitButton(exportBtn);
        exportButtonControl.setWidthUndefined();
        exportButtonControl.addStyleName(UIConstants.THEME_GRAY_LINK);
        exportButtonControl.setIcon(FontAwesome.EXTERNAL_LINK);

        OptionPopupContent popupButtonsControl = new OptionPopupContent();
        exportButtonControl.setContent(popupButtonsControl);

        Button exportPdfBtn = new Button("Pdf");
        FileDownloader pdfDownloader = new FileDownloader(constructStreamResource(ReportExportType.PDF));
        pdfDownloader.extend(exportPdfBtn);
        exportPdfBtn.setIcon(FontAwesome.FILE_PDF_O);
        popupButtonsControl.addOption(exportPdfBtn);

        Button exportExcelBtn = new Button("Excel");
        FileDownloader excelDownloader = new FileDownloader(constructStreamResource(ReportExportType.EXCEL));
        excelDownloader.extend(exportExcelBtn);
        exportExcelBtn.setIcon(FontAwesome.FILE_EXCEL_O);
        popupButtonsControl.addOption(exportExcelBtn);

        controlBtns.addComponent(exportButtonControl);
        controlBtns.setComponentAlignment(exportButtonControl, Alignment.TOP_RIGHT);
        controlBtns.setComponentAlignment(backBtn, Alignment.TOP_LEFT);
        controlBtns.setSizeFull();

        this.timeTrackingWrapper = new VerticalLayout();
        this.timeTrackingWrapper.setWidth("100%");
        contentWrapper.addComponent(this.timeTrackingWrapper);

        Calendar date = new GregorianCalendar();
        date.set(Calendar.DAY_OF_MONTH, 1);

        fromDate = date.getTime();
        date.add(Calendar.DAY_OF_MONTH, date.getActualMaximum(Calendar.DAY_OF_MONTH));
        toDate = date.getTime();

        fromDateField.setValue(fromDate);
        toDateField.setValue(toDate);

        searchCriteria = new ItemTimeLoggingSearchCriteria();

        searchCriteria.setRangeDate(new RangeDateSearchField(fromDate, toDate));
    } else {
        final Button backBtn = new Button("Back to Workboard");
        backBtn.addClickListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(final ClickEvent event) {
                EventBusFactory.getInstance()
                        .post(new ShellEvent.GotoProjectModule(TimeTrackingSummaryViewImpl.this, null));

            }
        });

        backBtn.addStyleName(UIConstants.THEME_GREEN_LINK);
        backBtn.setIcon(FontAwesome.ARROW_LEFT);

        VerticalLayout contentWrapper = new VerticalLayout();
        contentWrapper.setSpacing(true);

        Label infoLbl = new Label("You are not involved in any project yet to track time working");
        infoLbl.setWidthUndefined();
        contentWrapper.setMargin(true);
        contentWrapper.addComponent(infoLbl);
        contentWrapper.setComponentAlignment(infoLbl, Alignment.MIDDLE_CENTER);

        contentWrapper.addComponent(backBtn);
        contentWrapper.setComponentAlignment(backBtn, Alignment.MIDDLE_CENTER);
        this.addComponent(contentWrapper);
        this.setComponentAlignment(contentWrapper, Alignment.MIDDLE_CENTER);
    }
}

From source file:org.easyrec.utils.Benchmark.java

/**
 * Creates actions with a random timestamp starting at the beginning of the
 * year until current date.//from w w  w.j ava  2 s.  co m
 *
 * @param st
 * @param actionType
 * @param actions
 * @throws Exception
 */
private static void createActions(Statement st, int actions) throws Exception {

    int i = 0;
    int actionTypeId = 0;

    Calendar actionTime = Calendar.getInstance();
    Calendar currentTime = Calendar.getInstance();

    while (i < actions) {
        i++;
        //actionTime.set(
        //        actionTime.get(Calendar.YEAR),
        //        r.nextInt(Calendar.getInstance().get(Calendar.MONTH)+1),
        //        1
        //);
        actionTime.set(currentTime.get(Calendar.YEAR) - ACTIONS_TIME_RANGE + r.nextInt(ACTIONS_TIME_RANGE) + 1,
                r.nextInt(12) + 1, 1);

        actionTypeId = getActionTypeId();

        StringBuilder s = new StringBuilder().append("INSERT INTO ").append("  action").append("(")
                .append("  tenantId,").append("  userId,").append("  sessionId,").append("  ip,")
                .append("  itemId,").append("  itemTypeId,").append("  actionTypeId,");
        if (ACTION_TYPE_RATE == actionTypeId)
            s.append("  ratingValue,");
        s.append("  description,").append("  actionTime").append(")").append("VALUE (")
                .append(r.nextInt(NUMBER_OF_TENANTS) + 1).append("  ,").append(getUserId()).append(" ,'1',")
                .append(" '1',").append(getItemId()).append("  ,1,").append(actionTypeId);
        if (ACTION_TYPE_RATE == actionTypeId)
            s.append(",").append(r.nextInt(MAX_RATING_VALUE));
        s.append("  ,'1','").append(actionTime.get(Calendar.YEAR)).append("-")
                .append(actionTime.get(Calendar.MONTH) + 1).append("-")
                .append(r.nextInt(actionTime.getActualMaximum(Calendar.DAY_OF_MONTH)) + 1).append("'")
                .append(")");

        st.executeUpdate(s.toString());
        if (i % 100000 == 0) {
            System.out.println(i + " actions inserted.");
        }
    }
    System.out.println(i + " random actions created for " + NUMBER_OF_TENANTS
            + " tenant(s) with actiontypes (view: 99,4%, buy: 0,5%, rate: 0,1% ");
}

From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java

public List<List<Object>> getBedragenInMonthRange(String startMonth, String endMonth) throws ParseException {
    List<List<Object>> bedragenInMonthRange = new ArrayList<List<Object>>();

    for (String month : getAllMonths(startMonth, endMonth)) {
        SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
        Date startDate = dt.parse("01/" + month);
        Calendar c = Calendar.getInstance();
        c.setTime(startDate);//from   w ww . j a v a  2s .  c o m
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date endDate = c.getTime();

        Map<String, BigDecimal> bedragen = getPositiveNegativeBedragen(startDate, endDate);

        List<Object> values = new ArrayList<Object>();
        values.add(month);
        values.add(bedragen.get("POS"));
        values.add(bedragen.get("NEG"));

        bedragenInMonthRange.add(values);
    }

    return bedragenInMonthRange;
}

From source file:at.alladin.rmbt.statisticServer.UsageJSONResource.java

@Get("json")
public String request(final String entity) {
    JSONObject result = new JSONObject();
    int month = -1;
    int year = -1;
    try {//from  w w w . j  av  a 2  s .  c  o  m
        //parameters
        final Form getParameters = getRequest().getResourceRef().getQueryAsForm();
        try {

            if (getParameters.getNames().contains("month")) {
                month = Integer.parseInt(getParameters.getFirstValue("month"));
                if (month > 11 || month < 0) {
                    throw new NumberFormatException();
                }
            }
            if (getParameters.getNames().contains("year")) {
                year = Integer.parseInt(getParameters.getFirstValue("year"));
                if (year < 0) {
                    throw new NumberFormatException();
                }
            }
        } catch (NumberFormatException e) {
            return "invalid parameters";
        }

        Calendar now = new GregorianCalendar();
        Calendar monthBegin = new GregorianCalendar((year > 0) ? year : now.get(Calendar.YEAR),
                (month >= 0) ? month : now.get(Calendar.MONTH), 1);
        Calendar monthEnd = new GregorianCalendar((year > 0) ? year : now.get(Calendar.YEAR),
                (month >= 0) ? month : now.get(Calendar.MONTH),
                monthBegin.getActualMaximum(Calendar.DAY_OF_MONTH));
        //if now -> do not use the last day
        if (month == now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR)) {
            monthEnd = now;
            monthEnd.add(Calendar.DATE, -1);
        }

        JSONObject platforms = getPlatforms(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject usage = getClassicUsage(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsIOS = getVersions("iOS", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsAndroid = getVersions("Android", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsApplet = getVersions("Applet", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject networkGroupNames = getNetworkGroupName(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject networkGroupTypes = getNetworkGroupType(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        result.put("platforms", platforms);
        result.put("usage", usage);
        result.put("versions_ios", versionsIOS);
        result.put("versions_android", versionsAndroid);
        result.put("versions_applet", versionsApplet);
        result.put("network_group_names", networkGroupNames);
        result.put("network_group_types", networkGroupTypes);
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result.toString();
}

From source file:org.openmrs.module.sdmxhdintegration.reporting.extension.SDMXHDCrossSectionalReportRenderer.java

/**
  * @see org.openmrs.module.report.renderer.ReportRenderer#render(org.openmrs.module.report.ReportData, java.lang.String, java.io.OutputStream)
  *///from ww  w .j  av  a 2s.  c  om
@Override
public void render(ReportData reportData, String argument, OutputStream out)
        throws IOException, RenderingException {
    if (reportData.getDataSets().size() > 1) {
        throw new RenderingException(
                "This report contains multiple DataSets, this renderer does not support multiple DataSets");
    } else if (reportData.getDataSets().size() < 1) {
        throw new RenderingException("No DataSet defined in this report");
    }

    // get results dataSet
    org.openmrs.module.reporting.dataset.DataSet dataSet = reportData.getDataSets()
            .get(reportData.getDataSets().keySet().iterator().next());

    // get OMRS DSD
    Mapped<? extends DataSetDefinition> mappedOMRSDSD = reportData.getDefinition().getDataSetDefinitions()
            .get(reportData.getDefinition().getDataSetDefinitions().keySet().iterator().next());
    SDMXHDCohortIndicatorDataSetDefinition omrsDSD = (SDMXHDCohortIndicatorDataSetDefinition) mappedOMRSDSD
            .getParameterizable();

    // get SDMX-HD DSD
    SDMXHDService sdmxhdService = (SDMXHDService) Context.getService(SDMXHDService.class);
    SDMXHDMessage sdmxhdMessage = sdmxhdService.getMessage(omrsDSD.getSDMXHDMessageId());

    // get keyFamilyId
    KeyFamilyMapping keyFamilyMapping = sdmxhdService
            .getKeyFamilyMappingByReportDefinitionId(reportData.getDefinition().getId());
    String keyFamilyId = keyFamilyMapping.getKeyFamilyId();

    // get reporting month
    Date reportStartDate = (Date) reportData.getContext().getParameterValue("startDate");
    Date reportEndDate = (Date) reportData.getContext().getParameterValue("endDate");
    String timePeriod = null;

    // calculate time period and make sure reporting dates make sense
    String freq = sdmxhdMessage.getGroupElementAttributes().get("FREQ");
    if (freq != null) {
        if (freq.equals("M")) {
            // check that start and end date are the report are beginning and end day of the same month
            Calendar startCal = Calendar.getInstance();
            startCal.setTime(reportStartDate);

            int lastDay = startCal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int month = startCal.get(Calendar.MONTH);
            int year = startCal.get(Calendar.YEAR);

            Calendar endCal = Calendar.getInstance();
            endCal.setTime(reportEndDate);

            if (endCal.get(Calendar.MONTH) != month || endCal.get(Calendar.DAY_OF_MONTH) != lastDay
                    || endCal.get(Calendar.YEAR) != year) {
                throw new RenderingException(
                        "Frequency is set to monthly, but the reporting stat and end date don't correspond to a start and end date of a specific month");
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            timePeriod = sdf.format(reportStartDate);

        } else if (freq.equals("A")) {
            // check start and end date are beginning and end day of same year
            Calendar startCal = Calendar.getInstance();
            startCal.setTime(reportStartDate);

            int startDay = startCal.get(Calendar.DAY_OF_MONTH);
            int startMonth = startCal.get(Calendar.MONTH);
            int startYear = startCal.get(Calendar.YEAR);

            Calendar endCal = Calendar.getInstance();
            endCal.setTime(reportEndDate);

            int endDay = startCal.get(Calendar.DAY_OF_MONTH);
            int endMonth = startCal.get(Calendar.MONTH);
            int endYear = startCal.get(Calendar.YEAR);

            if (startDay != 1 || startMonth != Calendar.JANUARY || startYear != endYear || endDay != 31
                    || endMonth != Calendar.DECEMBER) {
                throw new RenderingException(
                        "Frequency is set to annual, but the reporting start and end date are not the begining of the end day of the same year");
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            timePeriod = sdf.format(reportStartDate);
        }
        // TODO other checks
    }

    try {
        String path = Context.getAdministrationService()
                .getGlobalProperty("sdmxhdintegration.messageUploadDir");
        ZipFile zf = new ZipFile(path + File.separator + sdmxhdMessage.getZipFilename());
        SDMXHDParser parser = new SDMXHDParser();
        org.jembi.sdmxhd.SDMXHDMessage sdmxhdData = parser.parse(zf);
        DSD sdmxhdDSD = sdmxhdData.getDsd();

        //Construct CDS object
        Sender p = new Sender();
        p.setId("OMRS");
        p.setName("OpenMRS");

        Header h = new Header();
        h.setId("SDMX-HD-CSDS");
        h.setTest(false);
        h.setTruncated(false);
        h.getName().addValue("en", "OpenMRS SDMX-HD Export");
        h.setPrepared(iso8601DateFormat.format(new Date()));
        h.getSenders().add(p);

        h.setReportingBegin(iso8601DateFormat.format(reportStartDate));
        h.setReportingEnd(iso8601DateFormat.format(reportEndDate));

        // Construct dataset
        DataSet sdmxhdDataSet = new DataSet();

        sdmxhdDataSet.setReportingBeginDate(iso8601DateFormat.format(reportStartDate));
        sdmxhdDataSet.setReportingEndDate(iso8601DateFormat.format(reportEndDate));

        // Add fixed dataset attributes
        Map<String, String> datasetElementAttributes = sdmxhdMessage.getDatasetElementAttributes();
        for (String attribute : datasetElementAttributes.keySet()) {
            String value = datasetElementAttributes.get(attribute);
            if (StringUtils.hasText(value)) {
                sdmxhdDataSet.addAttribute(attribute, value);
            }
        }

        // Construct group
        Group group = new Group();

        // Set time period and frequency
        if (timePeriod != null)
            group.addAttribute("TIME_PERIOD", timePeriod);
        if (timePeriod != null)
            group.addAttribute("FREQ", freq);

        // Set DataSet attributes
        Map<String, String> dataSetAttachedAttributes = omrsDSD.getDataSetAttachedAttributes();
        for (String key : dataSetAttachedAttributes.keySet()) {
            sdmxhdDataSet.getAttributes().put(key, dataSetAttachedAttributes.get(key));
        }

        // Holder for all sections. Will hold a default section if no explicit hierarchy is found in SL_ISET
        List<Section> sectionList = new ArrayList<Section>();

        // Iterate each row and colum of the dataset
        for (DataSetRow row : dataSet) {
            for (DataSetColumn column : row.getColumnValues().keySet()) {

                CohortIndicatorAndDimensionColumn cidColumn = (CohortIndicatorAndDimensionColumn) column;
                Object value = row.getColumnValues().get(column);
                String columnName = column.getName();

                //get the indicator code for this column
                CohortIndicator indicator = cidColumn.getIndicator().getParameterizable();
                String sdmxhdIndicatorName = omrsDSD.getSDMXHDMappedIndicator(indicator.getId());

                // get indicator/dataelement codelist
                Dimension indDim = sdmxhdDSD.getIndicatorOrDataElementDimension(keyFamilyId);
                CodeList indCodeList = sdmxhdDSD.getCodeList(indDim.getCodelistRef());
                Code indCode = indCodeList.getCodeByDescription(sdmxhdIndicatorName);

                //setup or get the section for this indicator
                Section section = getSectionHelper(indCode, sectionList, sdmxhdDSD); //indicator code, listOfSections, message

                //get the dimension for the list of indicators (CL_INDICATOR)
                Dimension indDimension = sdmxhdDSD.getDimension(indCodeList);

                //construct new (SDMX-HD) obs to contain the indicator value
                Obs obs = new Obs();

                // set the indicator attribute
                obs.getAttributes().put(indDimension.getConceptRef(), indCode.getValue());

                // set Section Attributes
                Map<String, String> seriesAttachedAttributes = omrsDSD.getSeriesAttachedAttributes()
                        .get(columnName);
                if (seriesAttachedAttributes != null) {
                    for (String key : seriesAttachedAttributes.keySet()) {
                        section.getAttributes().put(key, seriesAttachedAttributes.get(key));
                    }
                }

                // write dimensions to obs
                Map<String, String> dimensionOptions = cidColumn.getDimensionOptions();
                // for each dimension option for this column
                for (String omrsDimensionId : dimensionOptions.keySet()) {
                    Integer omrsDimensionIdInt = Integer.parseInt(omrsDimensionId);
                    // find sdmx-hd dimension name in mapping
                    String sdmxhdDimensionName = null;
                    Map<String, Integer> omrsMappedDimensions = omrsDSD.getOMRSMappedDimensions();
                    for (String sdmxhdDimensionNameTemp : omrsMappedDimensions.keySet()) {
                        if (omrsMappedDimensions.get(sdmxhdDimensionNameTemp).equals(omrsDimensionIdInt)) {
                            sdmxhdDimensionName = sdmxhdDimensionNameTemp;
                            break;
                        }
                    }
                    // find sdmx-hd dimension option name in mapping
                    String omrsDimensionOptionName = dimensionOptions.get(omrsDimensionId);
                    String sdmxhdDimensionOptionName = null;
                    Map<String, String> omrsMappedDimensionOptions = omrsDSD.getOMRSMappedDimensionOptions()
                            .get(sdmxhdDimensionName);
                    for (String sdmxhdDimensionOptionNameTemp : omrsMappedDimensionOptions.keySet()) {
                        if (omrsMappedDimensionOptions.get(sdmxhdDimensionOptionNameTemp)
                                .equals(omrsDimensionOptionName)) {
                            sdmxhdDimensionOptionName = sdmxhdDimensionOptionNameTemp;
                            break;
                        }
                    }
                    //find code corresponding to this dimension option
                    Dimension sdmxhdDimension = sdmxhdDSD.getDimension(sdmxhdDimensionName, keyFamilyId);
                    CodeList codeList = sdmxhdDSD.getCodeList(sdmxhdDimension.getCodelistRef());
                    Code code = codeList.getCodeByDescription(sdmxhdDimensionOptionName);
                    obs.addAttribute(sdmxhdDimensionName, code.getValue());
                }

                // add dimensions with default values
                List<String> mappedFixedDimensions = omrsDSD.getMappedFixedDimension(columnName);
                Map<String, String> fixedDimensionValues = omrsDSD.getFixedDimensionValues();
                for (String sdmxhdDimension : mappedFixedDimensions) {
                    if (fixedDimensionValues.get(sdmxhdDimension) != null) {
                        String fixedValue = fixedDimensionValues.get(sdmxhdDimension);
                        Dimension dimension = sdmxhdDSD.getDimension(sdmxhdDimension, keyFamilyId);
                        CodeList codeList = sdmxhdDSD.getCodeList(dimension.getCodelistRef());
                        Code code = codeList.getCodeByDescription(fixedValue);
                        obs.addAttribute(sdmxhdDimension, code.getValue());
                    }
                }

                // set Obs Attributes
                Map<String, String> obsAttachedAttributes = omrsDSD.getObsAttachedAttributes().get(columnName);
                if (obsAttachedAttributes != null) {
                    for (String key : obsAttachedAttributes.keySet()) {
                        obs.getAttributes().put(key, obsAttachedAttributes.get(key));
                    }
                }

                String primaryMeasure = sdmxhdDSD.getKeyFamily(keyFamilyId).getComponents().getPrimaryMeasure()
                        .getConceptRef();
                obs.elementName = primaryMeasure;

                // write value
                if (value instanceof CohortIndicatorAndDimensionResult) {
                    CohortIndicatorAndDimensionResult typedValue = (CohortIndicatorAndDimensionResult) value;
                    obs.getAttributes().put("value", typedValue.getValue().toString());
                } else {
                    obs.getAttributes().put("value", value.toString());
                }

                section.getObs().add(obs);
            }
        }

        // Add all sections to group
        for (Section section : sectionList) {
            group.getSections().add(section);
        }

        // Add group to dataset
        sdmxhdDataSet.getGroups().add(group);

        CSDS csds = new CSDS();
        csds.getDatasets().add(sdmxhdDataSet);
        csds.setHeader(h);

        // build up namespace
        KeyFamily keyFamily = sdmxhdDSD.getKeyFamily(keyFamilyId);
        String derivedNamespace = Constants.DERIVED_NAMESPACE_PREFIX + keyFamily.getAgencyID() + ":"
                + keyFamily.getId() + ":" + keyFamily.getVersion() + ":cross";
        String xml = csds.toXML(derivedNamespace);

        // output csds in original zip
        zf = new ZipFile(path + File.separator + sdmxhdMessage.getZipFilename());
        Utils.outputCsdsInDsdZip(zf, xml, out);
    } catch (IllegalArgumentException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (XMLStreamException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (ExternalRefrenceNotFoundException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (ValidationException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (SchemaValidationException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    }
}

From source file:com.mss.msp.util.DateUtility.java

/**
 * Last date/* www  .j ava2s.c o m*/
 */
public String LastMonthLastDate() throws ParseException {
    Calendar cal = Calendar.getInstance();
    int cur_year = cal.get(Calendar.YEAR);
    int cur_month = cal.get(Calendar.MONTH);
    int last_month = cur_month - 1;
    cal.set(cur_year, last_month, 1); //------>
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    return sdf.format(cal.getTime());
}

From source file:it.scoppelletti.mobilepower.types.SimpleDate.java

/**
 * Costruttore./*  www .jav  a2s  .  co  m*/
 * 
 * @param year  Anno.
 * @param month Mese.
 * @param day   Giorno.
 */
public SimpleDate(int year, int month, int day) {
    int min, max;
    Calendar cal = Calendar.getInstance();

    min = cal.getMinimum(Calendar.YEAR);
    max = cal.getMaximum(Calendar.YEAR);
    if (year < min || year > max) {
        throw new IllegalArgumentException(
                String.format("Argument year %1$d is ouf of range [%2$d, %3$d].", year, min, max));
    }
    cal.set(Calendar.YEAR, year);

    min = cal.getActualMinimum(Calendar.MONTH);
    max = cal.getActualMaximum(Calendar.MONTH);
    if (month < min || month > max) {
        throw new IllegalArgumentException(
                String.format("Argument month %1$d is ouf of range [%2$d, %3$d].", month, min, max));
    }
    cal.set(Calendar.MONTH, month);

    min = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
    max = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    if (day < min || day > max) {
        throw new IllegalArgumentException(
                String.format("Argument day %1$d is ouf of range [%2$d, %3$d].", day, min, max));
    }

    myYear = year;
    myMonth = month;
    myDay = day;
}