Example usage for org.joda.time DateTime getYear

List of usage examples for org.joda.time DateTime getYear

Introduction

In this page you can find the example usage for org.joda.time DateTime getYear.

Prototype

public int getYear() 

Source Link

Document

Get the year field value.

Usage

From source file:org.fenixedu.academic.service.CreateUnavailablePeriod.java

License:Open Source License

private static void sendEmail(Person person, DateTime begin, DateTime end, String justification,
        List<VigilantGroup> groups) {
    for (VigilantGroup group : groups) {
        String bccs = group.getContactEmail();

        String beginDate = begin.getDayOfMonth() + "/" + begin.getMonthOfYear() + "/" + begin.getYear() + " - "
                + String.format("%02d", begin.getHourOfDay()) + ":"
                + String.format("%02d", begin.getMinuteOfHour()) + "h";
        String endDate = end.getDayOfMonth() + "/" + end.getMonthOfYear() + "/" + end.getYear() + " - "
                + String.format("%02d", end.getHourOfDay()) + ":" + String.format("%02d", end.getMinuteOfHour())
                + "h";
        ;//from   w w  w .  j a v a 2s  . com
        String message = BundleUtil.getString("resources.VigilancyResources", "email.convoke.unavailablePeriod",
                new String[] { person.getName(), beginDate, endDate, justification });

        String subject = BundleUtil.getString("resources.VigilancyResources",
                "email.convoke.unavailablePeriod.subject", new String[] { group.getName() });

        Sender sender = Bennu.getInstance().getSystemSender();
        new Message(sender, new ConcreteReplyTo(group.getContactEmail()).asCollection(), Collections.EMPTY_LIST,
                subject, message, bccs);
    }
}

From source file:org.fenixedu.academic.servlet.taglib.GanttDiagramTagLib.java

License:Open Source License

private StringBuilder generateGanttDiagramInTimeMode(BigDecimal tableWidth) throws JspException {
    StringBuilder builder = new StringBuilder();

    if (!getEvents().isEmpty()) {
        if (isShowPeriod() && isShowObservations()) {
            builder.append("<table style=\"width:")
                    .append(tableWidth.add(BigDecimal.valueOf(FIXED_COLUMNS_SIZE_EM)))
                    .append("em;\" class=\"tcalendar thlight\">");
        } else {/*from  w w w  . j  av a  2  s  .  c  om*/
            builder.append("<table class=\"tcalendar thlight\">");
        }

        generateHeaders(builder);

        int numberOfUnits = getNumberOfUnits();

        String selectedEvent = getRequest().getParameter(getEventParameter());
        Object selectedEventObject = getRequest().getAttribute(getEventParameter());

        for (GanttDiagramEvent event : getEvents()) {

            String eventUrl = getRequest().getContextPath() + getEventUrl() + "&amp;" + getEventParameter()
                    + "=" + event.getGanttDiagramEventIdentifier();

            if (event.getGanttDiagramEventUrlAddOns() != null) {
                eventUrl = eventUrl.concat(event.getGanttDiagramEventUrlAddOns());
            }

            final LocalizedString diagramEventName = event.getGanttDiagramEventName();
            String eventName = diagramEventName == null ? "" : diagramEventName.getContent();
            String paddingStyle = "padding-left:" + event.getGanttDiagramEventOffset() * PADDING_LEFT_MULTIPLIER
                    + "px";

            if (event.getGanttDiagramEventIdentifier().equals(selectedEvent) || (selectedEventObject != null
                    && event.getGanttDiagramEventIdentifier().equals(selectedEventObject.toString()))) {
                builder.append("<tr class=\"selected\">");
            } else {
                builder.append("<tr>");
            }

            if (getViewTypeEnum() == ViewType.YEAR_DAILY) {
                builder.append("<td class=\"padded\">").append("<div class=\"nowrap\">");
                builder.append("<span style=\"").append(paddingStyle).append("\" title=\"").append(eventName)
                        .append("\">");
                builder.append("<a href=\"").append(eventUrl).append("&amp;month=")
                        .append(Month.values()[event.getGanttDiagramEventMonth() - 1].toString()).append("\">")
                        .append(eventName);
            } else {
                builder.append("<td class=\"padded\">")
                        .append("<div style=\"overflow:hidden; width: 14.5em;\" class=\"nowrap\">");
                builder.append("<span style=\"").append(paddingStyle).append("\" title=\"").append(eventName)
                        .append("\">");
                builder.append("<a href=\"").append(eventUrl).append("\">").append(eventName);
            }
            builder.append("</a></span></div></td>");

            for (DateTime day : getGanttDiagramObject().getDays()) {

                int startIndex = 0, endIndex = 0;
                int dayOfMonth = day.getDayOfMonth();
                int monthOfYear = day.getMonthOfYear();
                if (getViewTypeEnum() == ViewType.YEAR_DAILY) {
                    monthOfYear = event.getGanttDiagramEventMonth();
                }
                int year = day.getYear();
                YearMonthDay yearMonthDay = new YearMonthDay(year, monthOfYear, 1);

                isEventToMarkWeekendsAndHolidays = event.isGanttDiagramEventToMarkWeekendsAndHolidays();

                if (!isEventToMarkWeekendsAndHolidays) {
                    builder.append("<td style=\"width: ").append(convertToEm(numberOfUnits))
                            .append("em;\"><div style=\"position: relative;\">");
                }

                if (getViewTypeEnum() == ViewType.YEAR_DAILY) {
                    if (dayOfMonth > yearMonthDay.plusMonths(1).minusDays(1).getDayOfMonth()) {
                        addEmptyDiv(builder);
                        builder.append("</div></td>");
                        continue;
                    }
                }

                specialDiv = false;

                for (Interval interval : event.getGanttDiagramEventSortedIntervals()) {

                    toWrite = null;
                    toMark = true;
                    LocalDate localDate = yearMonthDay.withDayOfMonth(dayOfMonth).toLocalDate();
                    if ((event.getGanttDiagramEventDayType(interval) == DayType.SPECIFIC_DAYS)
                            || (event.getGanttDiagramEventDayType(interval) == DayType.WORKDAY)) {
                        if ((localDate.getDayOfWeek() == SATURDAY_IN_JODA_TIME)
                                || (localDate.getDayOfWeek() == SUNDAY_IN_JODA_TIME)
                                || (Holiday.isHoliday(localDate))) {
                            toMark = false;
                        }
                    }
                    if (isEventToMarkWeekendsAndHolidays) {
                        if (Holiday.isHoliday(localDate)) {
                            toWrite = F;
                        } else if (localDate.getDayOfWeek() == SATURDAY_IN_JODA_TIME) {
                            toWrite = S;
                        } else if (localDate.getDayOfWeek() == SUNDAY_IN_JODA_TIME) {
                            toWrite = D;
                        }
                    }

                    if (interval.getStart().getYear() <= year && interval.getEnd().getYear() >= year) {

                        if (interval.getStart().getYear() < year && interval.getEnd().getYear() > year) {
                            addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);
                        }
                        // Started in same year and Ended after
                        else if (interval.getStart().getYear() == year && interval.getEnd().getYear() > year) {

                            if (interval.getStart().getMonthOfYear() < monthOfYear) {
                                addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                            } else if (interval.getStart().getMonthOfYear() == monthOfYear) {

                                if (interval.getStart().getDayOfMonth() == dayOfMonth) {
                                    startIndex = calculateTimeOfDay(interval.getStart());
                                    addSpecialDiv(builder, convertToEm(numberOfUnits - (startIndex - 1)),
                                            convertToEm(startIndex - 1));

                                } else if (interval.getStart().getDayOfMonth() < dayOfMonth) {
                                    addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);
                                }
                            }
                        }
                        // Ended in same year and started before
                        else if (interval.getStart().getYear() < year && interval.getEnd().getYear() == year) {

                            if (interval.getEnd().getMonthOfYear() > monthOfYear) {
                                addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                            } else if (interval.getEnd().getMonthOfYear() == monthOfYear) {

                                if (interval.getEnd().getDayOfMonth() > dayOfMonth) {
                                    addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                                } else if (interval.getEnd().getDayOfMonth() == dayOfMonth) {
                                    endIndex = calculateTimeOfDay(interval.getEnd());
                                    addSpecialDiv(builder, convertToEm(endIndex), EMPTY_UNIT);
                                }
                            }
                        }
                        // Ended and Started In Same Year
                        else if (interval.getStart().getYear() == year && interval.getEnd().getYear() == year) {

                            if (interval.getStart().getMonthOfYear() <= monthOfYear
                                    && interval.getEnd().getMonthOfYear() >= monthOfYear) {

                                if (interval.getStart().getMonthOfYear() == monthOfYear
                                        && interval.getEnd().getMonthOfYear() > monthOfYear) {

                                    if (interval.getStart().getDayOfMonth() == dayOfMonth) {
                                        startIndex = calculateTimeOfDay(interval.getStart());
                                        addSpecialDiv(builder, convertToEm(numberOfUnits - (startIndex - 1)),
                                                convertToEm(startIndex - 1));

                                    } else if (interval.getStart().getDayOfMonth() < dayOfMonth) {
                                        addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);
                                    }

                                } else if (interval.getStart().getMonthOfYear() < monthOfYear
                                        && interval.getEnd().getMonthOfYear() == monthOfYear) {

                                    if (interval.getEnd().getDayOfMonth() > dayOfMonth) {
                                        addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                                    } else if (interval.getEnd().getDayOfMonth() == dayOfMonth) {
                                        endIndex = calculateTimeOfDay(interval.getEnd());
                                        addSpecialDiv(builder, convertToEm(endIndex), EMPTY_UNIT);
                                    }

                                } else if (interval.getStart().getMonthOfYear() < monthOfYear
                                        && interval.getEnd().getMonthOfYear() > monthOfYear) {
                                    addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                                } else if (interval.getStart().getMonthOfYear() == monthOfYear
                                        && interval.getEnd().getMonthOfYear() == monthOfYear) {

                                    if (interval.getStart().getDayOfMonth() <= dayOfMonth
                                            && interval.getEnd().getDayOfMonth() >= dayOfMonth) {

                                        if (event.isGanttDiagramEventIntervalsLongerThanOneDay()
                                                && (interval.getStart().getDayOfMonth() == dayOfMonth
                                                        || interval.getEnd().getDayOfMonth() > dayOfMonth)) {
                                            startIndex = calculateTimeOfDay(interval.getStart());
                                            addSpecialDiv(builder,
                                                    convertToEm(numberOfUnits - (startIndex - 1)),
                                                    convertToEm(startIndex - 1));
                                        } else if (interval.getStart().getDayOfMonth() == dayOfMonth
                                                && interval.getEnd().getDayOfMonth() > dayOfMonth) {
                                            startIndex = calculateTimeOfDay(interval.getStart());
                                            addSpecialDiv(builder,
                                                    convertToEm(numberOfUnits - (startIndex - 1)),
                                                    convertToEm(startIndex - 1));
                                        }

                                        else if (interval.getStart().getDayOfMonth() < dayOfMonth
                                                && interval.getEnd().getDayOfMonth() == dayOfMonth) {
                                            endIndex = calculateTimeOfDay(interval.getEnd());
                                            addSpecialDiv(builder, convertToEm(endIndex), EMPTY_UNIT);
                                        }

                                        else if (interval.getStart().getDayOfMonth() == dayOfMonth
                                                && interval.getEnd().getDayOfMonth() == dayOfMonth) {

                                            startIndex = calculateTimeOfDay(interval.getStart());
                                            endIndex = calculateTimeOfDay(interval.getEnd());

                                            if (startIndex == endIndex) {
                                                addSpecialDiv(builder, convertToEm(1),
                                                        convertToEm(startIndex - 1));
                                            } else {
                                                addSpecialDiv(builder, convertToEm((endIndex - startIndex) + 1),
                                                        convertToEm(startIndex - 1));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (!isEventToMarkWeekendsAndHolidays) {
                    builder.append("</div></td>");
                } else if (!specialDiv) {
                    builder.append("<td class=\"tdnomark\">");
                    if (dayOfMonth <= yearMonthDay.plusMonths(1).minusDays(1).getDayOfMonth()) {
                        LocalDate localDate = yearMonthDay.withDayOfMonth(dayOfMonth).toLocalDate();
                        if (Holiday.isHoliday(localDate)) {
                            builder.append(F);
                        } else if (localDate.getDayOfWeek() == SATURDAY_IN_JODA_TIME) {
                            builder.append("S");
                        } else if (localDate.getDayOfWeek() == SUNDAY_IN_JODA_TIME) {
                            builder.append("D");
                        }
                    }
                    builder.append("</td>");
                }
            }
            if (isShowPeriod()) {
                builder.append("<td class=\"padded smalltxt\" title=\"")
                        .append(event.getGanttDiagramEventPeriod())
                        .append("\"><div style=\"overflow:hidden;\" class=\"nowrap\">")
                        .append(event.getGanttDiagramEventPeriod()).append("</div></td>");
            }
            if (isShowObservations()) {
                builder.append("<td class=\"padded smalltxt\">")
                        .append(event.getGanttDiagramEventObservations()).append("</td>");
            }
            builder.append("</tr>");
        }
        insertNextAndBeforeLinks(builder);
        builder.append("</table>");
    }
    return builder;
}

From source file:org.fenixedu.academic.ui.struts.action.FenixEduVigilanciesContextListener.java

License:Open Source License

private static void notifyVigilantsOfDeletedEvaluation(WrittenEvaluation writtenEvaluation) {
    if (!writtenEvaluation.getVigilanciesSet().isEmpty()) {
        final Set<Person> tos = new HashSet<Person>();

        for (VigilantGroup group : VigilantGroup.getAssociatedVigilantGroups(writtenEvaluation)) {
            tos.clear();//ww w  .ja v a 2  s  .  c  om
            DateTime date = writtenEvaluation.getBeginningDateTime();
            String time = writtenEvaluation.getBeginningDateHourMinuteSecond().toString();
            String beginDateString = date.getDayOfMonth() + "-" + date.getMonthOfYear() + "-" + date.getYear();

            String subject = BundleUtil.getString("resources.VigilancyResources", "email.convoke.subject",
                    new String[] { writtenEvaluation.getName(), group.getName(), beginDateString, time });
            String body = BundleUtil.getString("resources.VigilancyResources",
                    "label.writtenEvaluationDeletedMessage",
                    new String[] { writtenEvaluation.getName(), beginDateString, time });
            for (Vigilancy vigilancy : writtenEvaluation.getVigilanciesSet()) {
                Person person = vigilancy.getVigilantWrapper().getPerson();
                tos.add(person);
            }
            Sender sender = Bennu.getInstance().getSystemSender();
            new Message(sender, new ConcreteReplyTo(group.getContactEmail()).asCollection(),
                    new Recipient(UserGroup.of(Person.convertToUsers(tos))).asCollection(), subject, body, "");

        }
    }
}

From source file:org.fenixedu.academic.ui.struts.action.FenixEduVigilanciesContextListener.java

License:Open Source License

private static void notifyVigilantsOfEditedEvaluation(EditWrittenEvaluationEvent event) {
    WrittenEvaluation writtenEvaluation = event.getInstance();
    Date dayDate = event.getDayDate();
    Date beginDate = event.getBeginDate();
    if (!writtenEvaluation.getVigilanciesSet().isEmpty() && (dayDate != writtenEvaluation.getDayDate()
            || timeModificationIsBiggerThanFiveMinutes(beginDate, writtenEvaluation.getBeginningDate()))) {
        final HashSet<Person> tos = new HashSet<Person>();

        // VigilantGroup group =
        // writtenEvaluation.getAssociatedVigilantGroups().iterator().next();
        for (VigilantGroup group : VigilantGroup.getAssociatedVigilantGroups(writtenEvaluation)) {
            tos.clear();/*from  ww  w.java 2  s.  c  o m*/
            DateTime date = writtenEvaluation.getBeginningDateTime();
            String time = writtenEvaluation.getBeginningDateHourMinuteSecond().toString();
            String beginDateString = date.getDayOfMonth() + "-" + date.getMonthOfYear() + "-" + date.getYear();

            String subject = String.format("[ %s - %s - %s %s ]",
                    new Object[] { writtenEvaluation.getName(), group.getName(), beginDateString, time });
            String body = String.format(
                    "Caro Vigilante,\n\nA prova de avaliao: %1$s %2$s - %3$s foi alterada para  %4$td-%4$tm-%4$tY - %5$tH:%5$tM.",
                    new Object[] { writtenEvaluation.getName(), beginDateString, time, dayDate, beginDate });

            for (Vigilancy vigilancy : writtenEvaluation.getVigilanciesSet()) {
                Person person = vigilancy.getVigilantWrapper().getPerson();
                tos.add(person);
            }
            Sender sender = Bennu.getInstance().getSystemSender();
            new Message(sender, new ConcreteReplyTo(group.getContactEmail()).asCollection(),
                    new Recipient(UserGroup.of(Person.convertToUsers(tos))).asCollection(), subject, body, "");
        }
    }
}

From source file:org.fenixedu.academic.ui.struts.action.operator.SubmitPhotoAction.java

License:Open Source License

public ActionForward photoUpload(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    PhotographUploadBean photo = getRenderedObject();
    RenderUtils.invalidateViewState();//from   w w  w .jav a  2s.  co  m
    String base64Thumbnail = request.getParameter("encodedThumbnail");
    String base64Image = request.getParameter("encodedPicture");
    if (base64Image != null && base64Thumbnail != null) {
        DateTime now = new DateTime();
        photo.setFilename("mylovelypic_" + now.getYear() + now.getMonthOfYear() + now.getDayOfMonth()
                + now.getHourOfDay() + now.getMinuteOfDay() + now.getSecondOfMinute() + ".png");
        photo.setBase64RawContent(base64Image.split(",")[1]);
        photo.setBase64RawThumbnail(base64Thumbnail.split(",")[1]);
        photo.setContentType(base64Image.split(",")[0].split(":")[1].split(";")[0]);
    }

    ActionMessages actionMessages = new ActionMessages();
    try (InputStream stream = photo.getFileInputStream()) {
        if (stream == null) {
            actionMessages.add("error", new ActionMessage("errors.fileRequired"));
            saveMessages(request, actionMessages);
            return preparePhotoUpload(mapping, actionForm, request, response);
        }
    }

    if (ContentType.getContentType(photo.getContentType()) == null) {
        actionMessages.add("error", new ActionMessage("errors.unsupportedFile"));
        saveMessages(request, actionMessages);
        return preparePhotoUpload(mapping, actionForm, request, response);
    }

    if (photo.getRawSize() > MAX_RAW_SIZE) {
        actionMessages.add("error", new ActionMessage("errors.fileTooLarge"));
        saveMessages(request, actionMessages);
        photo.deleteTemporaryFiles();
        return preparePhotoUpload(mapping, actionForm, request, response);
    }

    try {
        photo.processImage();
    } catch (UnableToProcessTheImage e) {
        actionMessages.add("error", new ActionMessage("errors.unableToProcessImage"));
        saveMessages(request, actionMessages);
        photo.deleteTemporaryFiles();
        return preparePhotoUpload(mapping, actionForm, request, response);
    }

    try {
        updatePersonPhoto(photo);
    } catch (Exception e) {
        actionMessages.add("error", new ActionMessage("errors.unableToSaveImage"));
        saveMessages(request, actionMessages);
        photo.deleteTemporaryFiles();
        return preparePhotoUpload(mapping, actionForm, request, response);
    }

    actionMessages.add("success", new ActionMessage("label.operator.submit.ok", ""));
    saveMessages(request, actionMessages);
    return preparePhotoUpload(mapping, actionForm, request, response);
}

From source file:org.fenixedu.academic.ui.struts.action.person.UploadPhotoDA.java

License:Open Source License

public ActionForward upload(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    PhotographUploadBean photo = getRenderedObject();
    RenderUtils.invalidateViewState();//from  w ww .jav a 2  s. co m
    String base64Thumbnail = request.getParameter("encodedThumbnail");
    String base64Image = request.getParameter("encodedPicture");
    if (base64Image != null && base64Thumbnail != null) {
        DateTime now = new DateTime();
        photo.setFilename("mylovelypic_" + now.getYear() + now.getMonthOfYear() + now.getDayOfMonth()
                + now.getHourOfDay() + now.getMinuteOfDay() + now.getSecondOfMinute() + ".png");
        photo.setBase64RawContent(base64Image.split(",")[1]);
        photo.setBase64RawThumbnail(base64Thumbnail.split(",")[1]);
        photo.setContentType(base64Image.split(",")[0].split(":")[1].split(";")[0]);
    }

    ActionMessages actionMessages = new ActionMessages();
    try (InputStream stream = photo.getFileInputStream()) {
        if (stream == null) {
            actionMessages.add("fileRequired", new ActionMessage("errors.fileRequired"));
            saveMessages(request, actionMessages);
            return prepare(mapping, actionForm, request, response);
        }
    }

    if (ContentType.getContentType(photo.getContentType()) == null) {
        actionMessages.add("fileUnsupported", new ActionMessage("errors.unsupportedFile"));
        saveMessages(request, actionMessages);
        return prepare(mapping, actionForm, request, response);
    }

    if (photo.getRawSize() > MAX_RAW_SIZE) {
        actionMessages.add("fileTooLarge", new ActionMessage("errors.fileTooLarge"));
        saveMessages(request, actionMessages);
        photo.deleteTemporaryFiles();
        return prepare(mapping, actionForm, request, response);
    }

    try {
        photo.processImage();
    } catch (UnableToProcessTheImage e) {
        actionMessages.add("unableToProcessImage", new ActionMessage("errors.unableToProcessImage"));
        saveMessages(request, actionMessages);
        photo.deleteTemporaryFiles();
        return prepare(mapping, actionForm, request, response);
    }
    photo.createTemporaryFiles();

    request.setAttribute("preview", true);
    request.setAttribute("photo", photo);
    return mapping.findForward("confirm");
}

From source file:org.fenixedu.spaces.ui.ListOccupationsController.java

License:Open Source License

@RequestMapping
public String list(Model model,
        @RequestParam(defaultValue = "#{new org.joda.time.DateTime().getMonthOfYear()}") int month,
        @RequestParam(defaultValue = "#{new org.joda.time.DateTime().getYear()}") int year,
        @RequestParam(defaultValue = "") String name) {
    DateTime now = new DateTime();
    int currentYear = now.getYear();
    model.addAttribute("years", IntStream.rangeClosed(currentYear - 100, currentYear + 10).boxed()
            .sorted((o1, o2) -> o2.compareTo(o1)).collect(Collectors.toList()));

    List<Partial> months = IntStream.rangeClosed(1, 12).boxed()
            .map(m -> new Partial(DateTimeFieldType.monthOfYear(), m)).collect(Collectors.toList());
    model.addAttribute("months", months);
    model.addAttribute("currentMonth", month);
    model.addAttribute("currentYear", year);
    model.addAttribute("occupations",
            occupationService.getOccupations(month, year, Authenticate.getUser(), name));
    model.addAttribute("name", name);
    return "occupations/list";
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

License:Open Source License

private XMLGregorianCalendar convertToXMLDateTime(DatatypeFactory dataTypeFactory, DateTime documentDate) {
    return dataTypeFactory.newXMLGregorianCalendar(documentDate.getYear(), documentDate.getMonthOfYear(),
            documentDate.getDayOfMonth(), documentDate.getHourOfDay(), documentDate.getMinuteOfHour(),
            documentDate.getSecondOfMinute(), 0, DatatypeConstants.FIELD_UNDEFINED);
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

License:Open Source License

private Header createSAFTHeader(DateTime startDate, DateTime endDate, FinantialInstitution finantialInstitution,
        String auditVersion) {//from   w  w w.  j ava  2 s.  c o  m

    Header header = new Header();
    DatatypeFactory dataTypeFactory;
    try {

        dataTypeFactory = DatatypeFactory.newInstance();

        // AuditFileVersion
        header.setAuditFileVersion(auditVersion);

        // BusinessName - Nome da Empresa
        header.setBusinessName(finantialInstitution.getCompanyName());
        header.setCompanyName(finantialInstitution.getName());

        // CompanyAddress
        AddressStructurePT companyAddress = null;
        //TODOJN Locale por resolver
        companyAddress = convertAddressToAddressPT(finantialInstitution.getAddress(),
                finantialInstitution.getZipCode(),
                finantialInstitution.getMunicipality() != null
                        ? finantialInstitution.getMunicipality().getLocalizedName(new Locale("pt"))
                        : "---",
                finantialInstitution.getAddress());
        header.setCompanyAddress(companyAddress);

        // CompanyID
        /*
         * Obtem -se pela concatena??o da conservat?ria do registo comercial
         * com o n?mero do registo comercial, separados pelo car?cter
         * espa?o. Nos casos em que n?o existe o registo comercial, deve ser
         * indicado o NIF.
         */
        header.setCompanyID(finantialInstitution.getComercialRegistrationCode());

        // CurrencyCode
        /*
         * 1.11 * C?digo de moeda (CurrencyCode) . . . . . . . Preencher com
         * ?EUR?
         */
        header.setCurrencyCode(finantialInstitution.getCurrency().getCode());

        // DateCreated
        DateTime now = new DateTime();
        header.setDateCreated(convertToXMLDateTime(dataTypeFactory, now));

        // Email
        // header.setEmail(StringUtils.EMPTY);

        // EndDate
        header.setEndDate(convertToXMLDateTime(dataTypeFactory, endDate));

        // Fax
        // header.setFax(StringUtils.EMPTY);

        // FiscalYear
        /*
         * Utilizar as regras do c?digo do IRC, no caso de per?odos
         * contabil?sticos n?o coincidentes com o ano civil. (Ex: per?odo de
         * tributa??o de 01 -10 -2008 a 30 -09 -2009 corresponde FiscalYear
         * 2008). Inteiro 4
         */
        header.setFiscalYear(endDate.getYear());

        // Ir obter a data do ?ltimo
        // documento(por causa de submeter em janeiro, documentos de
        // dezembro)

        // HeaderComment
        // header.setHeaderComment(org.apache.commons.lang.StringUtils.EMPTY);

        // ProductCompanyTaxID
        // Preencher com o NIF da entidade produtora do software
        header.setProductCompanyTaxID(SaftConfig.PRODUCT_COMPANY_TAX_ID());

        // ProductID
        /*
         * 1.16 * Nome do produto (ProductID). . . . . . . . . . . Nome do
         * produto que gera o SAF -T (PT) . . . . . . . . . . . Deve ser
         * indicado o nome comercial do software e o da empresa produtora no
         * formato ?Nome produto/nome empresa?.
         */
        header.setProductID(SaftConfig.PRODUCT_ID());

        // Product Version
        header.setProductVersion(SaftConfig.PRODUCT_VERSION());

        // SoftwareCertificateNumber
        header.setSoftwareCertificateNumber(BigInteger.valueOf(SaftConfig.SOFTWARE_CERTIFICATE_NUMBER()));

        // StartDate
        header.setStartDate(dataTypeFactory.newXMLGregorianCalendarDate(startDate.getYear(),
                startDate.getMonthOfYear(), startDate.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED));

        // TaxAccountingBasis
        /*
         * Deve ser preenchido com: contabilidade; facturao; ?I? ? dados
         * integrados de factura??o e contabilidade; ?S? ? autofactura??o;
         * ?P? ? dados parciais de factura??o
         */
        header.setTaxAccountingBasis("P");

        // TaxEntity
        /*
         * Identifica??o do estabelecimento (TaxEntity) No caso do ficheiro
         * de factura??o dever? ser especificado a que estabelecimento diz
         * respeito o ficheiro produzido, se aplic?vel, caso contr?rio,
         * dever? ser preenchido com a especifica??o ?Global?. No caso do
         * ficheiro de contabilidade ou integrado, este campo dever? ser
         * preenchido com a especifica??o ?Sede?. Texto 20
         */
        header.setTaxEntity("Global");

        // TaxRegistrationNumber
        /*
         * N?mero de identifica??o fiscal da empresa
         * (TaxRegistrationNumber). Preencher com o NIF portugu?s sem
         * espa?os e sem qualquer prefixo do pa?s. Inteiro 9
         */
        try {
            header.setTaxRegistrationNumber(Integer.parseInt(finantialInstitution.getFiscalNumber()));
        } catch (Exception ex) {
            throw new RuntimeException("Invalid Fiscal Number.");
        }

        // header.setTelephone(finantialInstitution.get);

        // header.setWebsite(finantialInstitution.getEmailContact());

        return header;
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.forgerock.openidm.util.DateUtil.java

License:CDDL license

/**
 * Returns a {@link String} representing a scheduler expression of the supplied date. The scheduler expression is of
 * the form: "{second} {minute} {hour} {day} {month} ? {year}".  
 *
 * For example, a scheduler expression for January 3, 2016 at 04:56 AM would be: "0 56 4 3 1 ? 2016". 
 * /*from  w w  w.ja v a  2  s.  co m*/
 * @param intervalString a {@link String} object representing an ISO 8601 time interval.
 * @return a {@link String} representing a scheduler expression of the supplied date.
 * @throws IllegalArgumentException if an error occurs while parsing the intervalString.
 */
public String getSchedulerExpression(DateTime date) throws IllegalArgumentException {
    StringBuilder sb = new StringBuilder().append(date.getSecondOfMinute()).append(" ")
            .append(date.getMinuteOfHour()).append(" ").append(date.getHourOfDay()).append(" ")
            .append(date.getDayOfMonth()).append(" ").append(date.getMonthOfYear()).append(" ").append("? ")
            .append(date.getYear());
    return sb.toString();
}