Example usage for org.joda.time YearMonthDay toString

List of usage examples for org.joda.time YearMonthDay toString

Introduction

In this page you can find the example usage for org.joda.time YearMonthDay toString.

Prototype

public String toString(String pattern) 

Source Link

Document

Output the date using the specified format pattern.

Usage

From source file:com.qubit.solution.fenixedu.integration.ldap.service.LdapIntegration.java

License:Open Source License

private static AttributesMap collectAttributeMap(final Person person) {
    String schooldCode = getSchoolCode();

    AttributesMap attributesMap = new AttributesMap();

    boolean isStudent = isStudent(person);
    boolean isTeacher = isTeacher(person);
    boolean isEmployee = isEmployee(person);
    boolean isAlumni = isAlumni(person);

    // REQUIRED//w  w  w  .j  a  va2 s .c  o m
    attributesMap.add(UL_STUDENT_ACTIVE_ATTRIBUTE + schooldCode, String.valueOf(isStudent).toUpperCase());
    attributesMap.add(UL_TEACHER_ACTIVE_ATTRIBUTE + schooldCode, String.valueOf(isTeacher).toUpperCase());
    attributesMap.add(UL_EMPLOYEE_ACTIVE_ATTRIBUTE + schooldCode, String.valueOf(isEmployee).toUpperCase());
    attributesMap.add(UL_ALUMNI_ATTRIBUTE + schooldCode, String.valueOf(isAlumni).toUpperCase());
    attributesMap.add(FULL_NAME_ATTRIBUTE, person.getName());
    attributesMap.add(GIVEN_NAME_ATTRIBUTE, person.getProfile().getGivenNames());
    String familyNames = person.getProfile().getFamilyNames();
    if (!StringUtils.isEmpty(familyNames)) {
        attributesMap.add(LAST_NAME_ATTRIBUTE, familyNames);
    } else {
        attributesMap.add(LAST_NAME_ATTRIBUTE, "-");
    }
    attributesMap.add(UL_BI_ATTRIBUTE, person.getDocumentIdNumber());
    YearMonthDay dateOfBirthYearMonthDay = person.getDateOfBirthYearMonthDay();
    if (dateOfBirthYearMonthDay != null) {
        attributesMap.add(UL_BIRTH_DATE_ATTRIBUTE, dateOfBirthYearMonthDay.toString("yyyyMMdd") + "000000Z");
    } else {
        attributesMap.add(UL_BIRTH_DATE_ATTRIBUTE, new DateTime().toString("yyyyMMddHHmmss.SSS") + "Z");
    }

    // OPTIONAL

    // Jos Lima said during the presentation of 1st year 1st time on the
    // 25th August
    // 2015 that we should send the personal email as soon as you have it,
    // even if not
    // validated yet.
    //
    // 25 August 2015
    Optional<? extends PartyContact> personalEmail = person.getPartyContactsSet().stream()
            .filter(partyContact -> partyContact instanceof EmailAddress
                    && Boolean.TRUE.equals(partyContact.getActive()) && partyContact.isPersonalType())
            .findFirst();
    if (personalEmail.isPresent()) {
        attributesMap.add(UL_EXTERNAL_EMAIL_ADDR_ATTRIBUTE, personalEmail.get().getPresentationValue());
    } else {
        attributesMap.add(UL_EXTERNAL_EMAIL_ADDR_ATTRIBUTE, person.getInstitutionalEmailAddressValue());
    }

    Gender gender = person.getGender();
    if (gender != null) {
        attributesMap.add(UL_SEX_ATTRIBUTE, gender.toString().substring(0, 1));
    }
    Country countryOfBirth = person.getCountryOfBirth();
    if (countryOfBirth != null) {
        attributesMap.add(CO_ATTRIBUTE, countryOfBirth.getName());
    }
    PhysicalAddress defaultPhysicalAddress = person.getDefaultPhysicalAddress();
    if (defaultPhysicalAddress != null && !StringUtils.isEmpty(defaultPhysicalAddress.getAddress())
            && !StringUtils.isEmpty(defaultPhysicalAddress.getPostalCode())) {
        attributesMap.add(UL_POSTAL_ADDR_ATTRIBUTE, defaultPhysicalAddress.getAddress());
        attributesMap.add(UL_POSTAL_CODE_ATTRIBUTE, defaultPhysicalAddress.getPostalCode());
    }
    attributesMap.add(UL_INTERNAL_EMAIL_ADDR_ATTRIBUTE + schooldCode,
            person.getInstitutionalEmailAddressValue());

    if (isStudent) {
        attributesMap.add(UL_ROLE_ATTRIBUTE, "STUDENT");
    }
    if (isTeacher) {
        attributesMap.add(UL_ROLE_ATTRIBUTE, "TEACHER");
    }
    if (isEmployee) {
        attributesMap.add(UL_ROLE_ATTRIBUTE, "EMPLOYEE");
    }

    CgdCard cgdCard = CgdCard.findByPerson(person);
    if (cgdCard != null) {
        attributesMap.add(UL_MIFARE_ATTRIBUTE + getSchoolCode(), cgdCard.getMifareCode());
    }

    if (person.getStudent() != null) {
        collecStudentAttributes(person.getStudent(), attributesMap);
    }

    return attributesMap;
}

From source file:net.sourceforge.fenixedu.dataTransferObject.InfoLesson.java

License:Open Source License

public String getNextPossibleLessonInstanceDate() {
    YearMonthDay day = getLesson().getNextPossibleLessonInstanceDate();
    return day != null ? day.toString("dd/MM/yyyy") : "-";
}

From source file:net.sourceforge.fenixedu.domain.alumni.AlumniReportFile.java

License:Open Source License

private void addPersonalDataRow(Spreadsheet sheet, String alumniName, Integer studentNumber, Person person,
        Alumni alumni) {/*  w  w w .  j  a va2s . co m*/
    // "NOME", "NUMERO_ALUNO", "DATA_NASCIMENTO", "MORADA", "COD_POSTAL",
    // "PAIS",
    // "EMAIL_PESSOAL", "EMAIL_ENVIAR"
    // "TELEFONE", "TELEMOVEL", "REGISTERED_WHEN"
    final Row row = sheet.addRow();
    row.setCell(alumniName);
    row.setCell(studentNumber);
    final YearMonthDay dateOfBirth = person.getDateOfBirthYearMonthDay();
    row.setCell(dateOfBirth == null ? NOT_AVAILABLE : dateOfBirth.toString("dd/MM/yyyy"));
    row.setCell(hasLastPersonalAddress(person) ? getLastPersonalAddress(person).getAddress() : NOT_AVAILABLE);
    row.setCell(hasLastPersonalAddress(person) ? getLastPersonalAddress(person).getAreaCode() : NOT_AVAILABLE);
    row.setCell(hasLastPersonalAddress(person) ? getLastPersonalAddress(person).getArea() : NOT_AVAILABLE);
    row.setCell(hasLastPersonalAddress(person) ? getLastPersonalAddress(person).getCountryOfResidenceName()
            : NOT_AVAILABLE);
    row.setCell(hasPersonalEmail(person) ? getPersonalEmail(person).getValue() : NOT_AVAILABLE);
    row.setCell(hasSendingEmail(person) ? getSendingEmail(person) : NOT_AVAILABLE);
    row.setCell(hasPersonalPhone(person) ? getPersonalPhone(person).getNumber() : NOT_AVAILABLE);
    row.setCell(hasRegisteredWhen(alumni) ? alumni.getRegisteredWhen().toString("yyyy-MM-dd") : NOT_AVAILABLE);
}

From source file:net.sourceforge.fenixedu.domain.reports.RaidesCommonReportFieldsWrapper.java

License:Open Source License

public static Row reportRaidesFields(final Spreadsheet sheet, final Registration registration,
        List<Registration> registrationPath, ExecutionYear executionYear, final CycleType cycleType,
        final boolean concluded, final YearMonthDay conclusionDate, BigDecimal average, boolean graduation) {

    final Row row = sheet.addRow();
    final Person graduate = registration.getPerson();
    //List<Registration> registrationPath = getFullRegistrationPath(registration);
    Registration sourceRegistration = registrationPath.iterator().next();
    final PersonalInformationBean personalInformationBean = registration
            .getPersonalInformationBean(executionYear);
    StudentCurricularPlan lastStudentCurricularPlan = registration.getLastStudentCurricularPlan();

    // Ciclo//  ww w . ja  v  a  2  s. c  o  m
    row.setCell(cycleType.getDescription());

    // Concludo
    row.setCell(String.valueOf(concluded));

    // Mdia do Ciclo
    if (graduation) {
        row.setCell(concluded ? printBigDecimal(average.setScale(0, BigDecimal.ROUND_HALF_EVEN))
                : printBigDecimal(average));
    } else {
        row.setCell(concluded
                ? lastStudentCurricularPlan.getCycle(cycleType).getCurriculum().getAverage().toPlainString()
                : "n/a");
    }

    // Data de Concluso
    row.setCell(conclusionDate != null ? conclusionDate.toString("dd-MM-yyyy") : "");

    // Data de Incio
    row.setCell(registration.getStartDate() != null ? registration.getStartDate().toString("dd-MM-yyyy") : "");

    // N de aluno
    row.setCell(registration.getNumber());

    // Tipo Identificao
    row.setCell(graduate.getIdDocumentType().getLocalizedName());

    // N de Identificao
    row.setCell(graduate.getDocumentIdNumber());

    // Dgitos de Controlo
    row.setCell(graduate.getIdentificationDocumentExtraDigitValue());

    // Verso Doc. Identificao
    row.setCell(graduate.getIdentificationDocumentSeriesNumberValue());

    // Nome
    row.setCell(registration.getName());

    // Sexo
    row.setCell(graduate.getGender().toString());

    // Data de Nascimento
    row.setCell(graduate.getDateOfBirthYearMonthDay() != null
            ? graduate.getDateOfBirthYearMonthDay().toString("dd-MM-yyyy")
            : "n/a");

    // Pas de Nascimento
    row.setCell(graduate.getCountryOfBirth() != null ? graduate.getCountryOfBirth().getName() : "n/a");

    // Pas de Nacionalidade
    row.setCell(graduate.getCountry() != null ? graduate.getCountry().getName() : "n/a");

    // Tipo Curso
    row.setCell(registration.getDegreeType().getLocalizedName());

    // Nome Curso
    row.setCell(registration.getDegree().getNameI18N().getContent());

    // Sigla Curso
    row.setCell(registration.getDegree().getSigla());

    // Ramos do currculo do aluno
    final StringBuilder majorBranches = new StringBuilder();
    final StringBuilder minorBranches = new StringBuilder();
    for (final BranchCurriculumGroup group : lastStudentCurricularPlan.getBranchCurriculumGroups()) {
        if (group.isMajor()) {
            majorBranches.append(group.getName().toString()).append(",");
        } else if (group.isMinor()) {
            minorBranches.append(group.getName().toString()).append(",");
        }
    }

    // Ramo Principal
    if (majorBranches.length() > 0) {
        row.setCell(majorBranches.deleteCharAt(majorBranches.length() - 1).toString());
    } else {
        row.setCell("");
    }

    // Ramo Secundro
    if (minorBranches.length() > 0) {
        row.setCell(minorBranches.deleteCharAt(minorBranches.length() - 1).toString());
    } else {
        row.setCell("");
    }

    // Ano Curricular
    row.setCell(registration.getCurricularYear(executionYear));

    // Ano de Ingresso no Curso Actual
    row.setCell(sourceRegistration.getStartExecutionYear().getName());

    // N de anos lectivos de inscrio no Curso actual
    int numberOfEnrolmentYears = 0;
    for (Registration current : registrationPath) {
        numberOfEnrolmentYears += current.getNumberOfYearsEnrolledUntil(executionYear);
    }
    row.setCell(numberOfEnrolmentYears);

    // ltimo ano em que esteve inscrito
    row.setCell(registration.getLastEnrolmentExecutionYear() != null
            ? registration.getLastEnrolmentExecutionYear().getName()
            : "");

    // Regime de frequncia curso: Tempo integral/Tempo Parcial
    row.setCell(registration.getRegimeType(executionYear) != null
            ? registration.getRegimeType(executionYear).getName()
            : "");

    // Tipo de Aluno (AFA, AM, ERASMUS, etc)
    row.setCell(
            registration.getRegistrationProtocol() != null ? registration.getRegistrationProtocol().getCode()
                    : "");

    // Regime de Ingresso no Curso Actual (cdigo)
    Ingression ingression = sourceRegistration.getIngression();
    if (ingression == null && sourceRegistration.getStudentCandidacy() != null) {
        ingression = sourceRegistration.getStudentCandidacy().getIngression();
    }
    row.setCell(ingression != null ? ingression.getName() : "");

    // Regime de Ingresso no Curso Actual (designao)
    row.setCell(ingression != null ? ingression.getFullDescription() : "");

    // estabelecimento do grau preced.: Instituio onde esteve
    // inscrito mas no obteve grau, (e.g: transferencias, mudanas de
    // curso...)
    row.setCell(personalInformationBean.getPrecedentInstitution() != null
            ? personalInformationBean.getPrecedentInstitution().getName()
            : "");
    // curso grau preced.
    row.setCell(personalInformationBean.getPrecedentDegreeDesignation() != null
            ? personalInformationBean.getPrecedentDegreeDesignation()
            : "");

    // estabelec. curso habl anterior compl (se o aluno ingressou por uma via
    // diferente CNA, e deve ser IST caso o aluno tenha estado matriculado noutro curso do IST)
    row.setCell(personalInformationBean.getInstitution() != null
            ? personalInformationBean.getInstitution().getName()
            : "");

    // curso habl anterior compl (se o aluno ingressou por uma via diferente CNA, e
    // deve ser IST caso o aluno tenha estado matriculado noutro curso do IST)
    row.setCell(personalInformationBean.getDegreeDesignation());

    // n inscries no curso preced. (conta uma por cada ano)
    row.setCell(personalInformationBean.getNumberOfPreviousYearEnrolmentsInPrecedentDegree() != null
            ? personalInformationBean.getNumberOfPreviousYearEnrolmentsInPrecedentDegree().toString()
            : "");

    // Nota de Ingresso
    Double entryGrade = null;
    if (registration.getStudentCandidacy() != null) {
        entryGrade = registration.getStudentCandidacy().getEntryGrade();
    }

    row.setCell(printDouble(entryGrade));

    // Opo de Ingresso
    Integer placingOption = null;
    if (registration.getStudentCandidacy() != null) {
        placingOption = registration.getStudentCandidacy().getPlacingOption();
    }

    row.setCell(placingOption);

    // Estado Civil
    row.setCell(personalInformationBean.getMaritalStatus() != null
            ? personalInformationBean.getMaritalStatus().toString()
            : registration.getPerson().getMaritalStatus().toString());

    // Pas de Residncia Permanente
    if (personalInformationBean.getCountryOfResidence() != null) {
        row.setCell(personalInformationBean.getCountryOfResidence().getName());
    } else {
        row.setCell(registration.getStudent().getPerson().getCountryOfResidence() != null
                ? registration.getStudent().getPerson().getCountryOfResidence().getName()
                : "");
    }

    // Distrito de Residncia Permanente
    if (personalInformationBean.getDistrictSubdivisionOfResidence() != null) {
        row.setCell(personalInformationBean.getDistrictSubdivisionOfResidence().getDistrict().getName());
    } else {
        row.setCell(registration.getStudent().getPerson().getDistrictOfResidence());
    }

    // Concelho de Residncia Permanente
    if (personalInformationBean.getDistrictSubdivisionOfResidence() != null) {
        row.setCell(personalInformationBean.getDistrictSubdivisionOfResidence().getName());
    } else {
        row.setCell(registration.getStudent().getPerson().getDistrictSubdivisionOfResidence());
    }

    // Deslocado da Residncia Permanente
    if (personalInformationBean.getDislocatedFromPermanentResidence() != null) {
        row.setCell(personalInformationBean.getDislocatedFromPermanentResidence().toString());
    } else {
        row.setCell("");
    }

    // Nvel de Escolaridade do Pai
    if (personalInformationBean.getFatherSchoolLevel() != null) {
        row.setCell(personalInformationBean.getFatherSchoolLevel().getName());
    } else {
        row.setCell("");
    }

    // Nvel de Escolaridade da Me
    if (personalInformationBean.getMotherSchoolLevel() != null) {
        row.setCell(personalInformationBean.getMotherSchoolLevel().getName());
    } else {
        row.setCell("");
    }

    // Condio perante a situao na profisso/Ocupao do
    // Pai
    if (personalInformationBean.getFatherProfessionalCondition() != null) {
        row.setCell(personalInformationBean.getFatherProfessionalCondition().getName());
    } else {
        row.setCell("");
    }

    // Condio perante a situao na profisso/Ocupao da
    // Me
    if (personalInformationBean.getMotherProfessionalCondition() != null) {
        row.setCell(personalInformationBean.getMotherProfessionalCondition().getName());
    } else {
        row.setCell("");
    }

    // Profisso do Pai
    if (personalInformationBean.getFatherProfessionType() != null) {
        row.setCell(personalInformationBean.getFatherProfessionType().getName());
    } else {
        row.setCell("");
    }

    // Profisso da Me
    if (personalInformationBean.getMotherProfessionType() != null) {
        row.setCell(personalInformationBean.getMotherProfessionType().getName());
    } else {
        row.setCell("");
    }

    // Profisso do Aluno
    if (personalInformationBean.getProfessionType() != null) {
        row.setCell(personalInformationBean.getProfessionType().getName());
    } else {
        row.setCell("");
    }

    // Data preenchimento dados RAIDES
    if (personalInformationBean.getLastModifiedDate() != null) {
        DateTime dateTime = personalInformationBean.getLastModifiedDate();
        row.setCell(dateTime.getYear() + "-" + dateTime.getMonthOfYear() + "-" + dateTime.getDayOfMonth());
    } else {
        row.setCell("");
    }

    // Estatuto de Trabalhador Estudante introduzido pelo aluno
    if (personalInformationBean.getProfessionalCondition() != null) {
        row.setCell(personalInformationBean.getProfessionalCondition().getName());
    } else {
        row.setCell("");
    }

    // Estatuto de Trabalhador Estudante 1 semestre do ano a que se
    // referem
    // os dados
    boolean working1Found = false;
    for (StudentStatute statute : registration.getStudent().getStudentStatutesSet()) {
        if (statute.getStatuteType() == StudentStatuteType.WORKING_STUDENT
                && statute.isValidInExecutionPeriod(executionYear.getFirstExecutionPeriod())) {
            working1Found = true;
            break;
        }
    }
    row.setCell(String.valueOf(working1Found));

    // Estatuto de Trabalhador Estudante 1 semestre do ano a que se
    // referem
    // os dados
    boolean working2Found = false;
    for (StudentStatute statute : registration.getStudent().getStudentStatutesSet()) {
        if (statute.getStatuteType() == StudentStatuteType.WORKING_STUDENT
                && statute.isValidInExecutionPeriod(executionYear.getLastExecutionPeriod())) {
            working2Found = true;
            break;
        }
    }
    row.setCell(String.valueOf(working2Found));

    // Bolseiro (info. RAIDES)
    if (personalInformationBean.getGrantOwnerType() != null) {
        row.setCell(personalInformationBean.getGrantOwnerType().getName());
    } else {
        row.setCell("");
    }

    // Instituio que atribuiu a bolsa
    if (personalInformationBean.getGrantOwnerType() != null && personalInformationBean.getGrantOwnerType()
            .equals(GrantOwnerType.OTHER_INSTITUTION_GRANT_OWNER)) {
        row.setCell(personalInformationBean.getGrantOwnerProviderName());
    } else {
        row.setCell("");
    }

    // Bolseiro (info. oficial)
    boolean sasFound = false;
    for (StudentStatute statute : registration.getStudent().getStudentStatutesSet()) {
        if (statute.getStatuteType() == StudentStatuteType.SAS_GRANT_OWNER
                && statute.isValidInExecutionPeriod(executionYear.getFirstExecutionPeriod())) {
            sasFound = true;
            break;
        }
    }
    row.setCell(String.valueOf(sasFound));

    // Grau Precedente
    row.setCell(personalInformationBean.getPrecedentSchoolLevel() != null
            ? personalInformationBean.getPrecedentSchoolLevel().getName()
            : "");

    // Outro Grau Precedente
    row.setCell(personalInformationBean.getOtherPrecedentSchoolLevel());

    // grau da habl anterior compl
    row.setCell(personalInformationBean.getSchoolLevel() != null
            ? personalInformationBean.getSchoolLevel().getName()
            : "");

    // Codigo do grau habl anterior
    DegreeDesignation designation = DegreeDesignation.readByNameAndSchoolLevel(
            personalInformationBean.getDegreeDesignation(), personalInformationBean.getPrecedentSchoolLevel());
    row.setCell(designation != null ? designation.getDegreeClassification().getCode() : "");

    // Outro grau da habl anterior compl
    row.setCell(personalInformationBean.getOtherSchoolLevel());

    // Pas de Habilitao Anterior ao Curso Actual
    row.setCell(personalInformationBean.getCountryWhereFinishedPreviousCompleteDegree() != null
            ? personalInformationBean.getCountryWhereFinishedPreviousCompleteDegree().getName()
            : "");

    // Pas de Habilitao do 12 ano ou equivalente
    row.setCell(personalInformationBean.getCountryWhereFinishedHighSchoolLevel() != null
            ? personalInformationBean.getCountryWhereFinishedHighSchoolLevel().getName()
            : "");

    // Ano de concluso da habilitao anterior
    row.setCell(personalInformationBean.getConclusionYear());

    // Nota de concluso da habilitao anterior
    row.setCell(
            personalInformationBean.getConclusionGrade() != null ? personalInformationBean.getConclusionGrade()
                    : "");

    MobilityAgreement mobilityAgreement = null;
    ExecutionInterval chosenCandidacyInterval = null;
    //getting the last mobility program done
    for (OutboundMobilityCandidacySubmission outboundCandidacySubmission : registration
            .getOutboundMobilityCandidacySubmissionSet()) {
        if (outboundCandidacySubmission.getSelectedCandidacy() != null
                && outboundCandidacySubmission.getSelectedCandidacy().getSelected()) {
            ExecutionInterval candidacyInterval = outboundCandidacySubmission
                    .getOutboundMobilityCandidacyPeriod().getExecutionInterval();
            //the candidacies are made in the previous year
            if (candidacyInterval.getAcademicInterval().isBefore(executionYear.getAcademicInterval())) {
                if (mobilityAgreement != null) {
                    if (!candidacyInterval.getAcademicInterval()
                            .isAfter(chosenCandidacyInterval.getAcademicInterval())) {
                        continue;
                    }
                }
                mobilityAgreement = outboundCandidacySubmission.getSelectedCandidacy()
                        .getOutboundMobilityCandidacyContest().getMobilityAgreement();
                chosenCandidacyInterval = candidacyInterval;
            }
        }
    }
    // Programa de mobilidade
    row.setCell(mobilityAgreement != null ? mobilityAgreement.getMobilityProgram().getName().getContent() : "");

    // Pas de mobilidade
    row.setCell(mobilityAgreement != null ? mobilityAgreement.getUniversityUnit().getCountry().getName() : "");

    // Durao do programa de mobilidade
    row.setCell(personalInformationBean.getMobilityProgramDuration() != null ? BundleUtil
            .getString(Bundle.ENUMERATION, personalInformationBean.getMobilityProgramDuration().name()) : "");

    // Tipo de Estabelecimento Frequentado no Ensino Secundrio
    if (personalInformationBean.getHighSchoolType() != null) {
        row.setCell(personalInformationBean.getHighSchoolType().getName());
    } else {
        row.setCell("");
    }

    int totalEnrolmentsInPreviousYear = 0;
    int totalEnrolmentsApprovedInPreviousYear = 0;
    //int totalEnrolmentsInFirstSemester = 0;
    double totalEctsConcludedUntilPreviousYear = 0d;
    for (final CycleCurriculumGroup cycleCurriculumGroup : lastStudentCurricularPlan
            .getInternalCycleCurriculumGrops()) {

        totalEctsConcludedUntilPreviousYear += cycleCurriculumGroup
                .getCreditsConcluded(executionYear.getPreviousExecutionYear());

        totalEnrolmentsInPreviousYear += cycleCurriculumGroup
                .getEnrolmentsBy(executionYear.getPreviousExecutionYear()).size();

        for (final Enrolment enrolment : cycleCurriculumGroup
                .getEnrolmentsBy(executionYear.getPreviousExecutionYear())) {
            if (enrolment.isApproved()) {
                totalEnrolmentsApprovedInPreviousYear++;
            }
        }

        //       totalEnrolmentsInFirstSemester += cycleCurriculumGroup.getEnrolmentsBy(executionYear.getFirstExecutionPeriod())
        //          .size();
    }

    // Total de ECTS inscritos no total do ano
    double totalCreditsEnrolled = 0d;
    for (Enrolment enrollment : lastStudentCurricularPlan.getEnrolmentsByExecutionYear(executionYear)) {
        totalCreditsEnrolled += enrollment.getEctsCredits();
    }
    row.setCell(printDouble(totalCreditsEnrolled));

    // Total de ECTS concludos at ao fim do ano lectivo anterior ao
    // que se
    // referem os dados (neste caso at ao fim de 2007/08) no curso actual
    double totalCreditsDismissed = 0d;
    for (Credits credits : lastStudentCurricularPlan.getCreditsSet()) {
        if (credits.isEquivalence()) {
            totalCreditsDismissed += credits.getEnrolmentsEcts();
        }
    }
    row.setCell(printDouble(totalEctsConcludedUntilPreviousYear));

    // N de Disciplinas Inscritos no ano lectivo anterior ao que se
    // referem
    // os dados
    row.setCell(totalEnrolmentsInPreviousYear);

    // N de Disciplinas Aprovadas no ano lectivo anterior ao que se
    // referem
    // os dados
    row.setCell(totalEnrolmentsApprovedInPreviousYear);

    // N de Inscries Externas no ano a que se referem os dados
    ExtraCurriculumGroup extraCurriculumGroup = lastStudentCurricularPlan.getExtraCurriculumGroup();
    int extraCurricularEnrolmentsCount = extraCurriculumGroup != null
            ? extraCurriculumGroup.getEnrolmentsBy(executionYear).size()
            : 0;

    for (final CycleCurriculumGroup cycleCurriculumGroup : lastStudentCurricularPlan
            .getExternalCurriculumGroups()) {
        extraCurricularEnrolmentsCount += cycleCurriculumGroup.getEnrolmentsBy(executionYear).size();
    }

    if (lastStudentCurricularPlan.hasPropaedeuticsCurriculumGroup()) {
        extraCurricularEnrolmentsCount += lastStudentCurricularPlan.getPropaedeuticCurriculumGroup()
                .getEnrolmentsBy(executionYear).size();
    }

    row.setCell(extraCurricularEnrolmentsCount);

    // Estados de matrcula
    SortedSet<RegistrationState> states = new TreeSet<RegistrationState>(RegistrationState.DATE_COMPARATOR);
    for (Registration current : registrationPath) {
        states.addAll(current.getRegistrationStatesSet());
    }
    RegistrationState previousYearState = null;
    RegistrationState currentYearState = null;
    for (RegistrationState state : states) {
        if (!state.getStateDate().isAfter(
                executionYear.getPreviousExecutionYear().getEndDateYearMonthDay().toDateTimeAtMidnight())) {
            previousYearState = state;
        }
        if (!state.getStateDate().isAfter(executionYear.getEndDateYearMonthDay().toDateTimeAtMidnight())) {
            currentYearState = state;
        }
    }

    // Estado da matrcula no ano lectivo anterior ao que se referem os
    // dados
    row.setCell(previousYearState != null ? previousYearState.getStateType().getDescription() : "n/a");

    // Estado (da matrcula) no ano a que se referem os dados
    row.setCell(currentYearState != null ? currentYearState.getStateType().getDescription() : "n/a");

    // Data do estado de matrcula
    row.setCell(currentYearState != null ? currentYearState.getStateDate().toString("dd-MM-yyyy") : "n/a");

    // N ECTS do 1 Ciclo concludos at ao fim do ano lectivo
    // anterior ao que se referem os dados
    final CycleCurriculumGroup firstCycleCurriculumGroup = lastStudentCurricularPlan.getRoot()
            .getCycleCurriculumGroup(CycleType.FIRST_CYCLE);
    row.setCell(firstCycleCurriculumGroup != null
            ? printBigDecimal(firstCycleCurriculumGroup.getCurriculum(executionYear).getSumEctsCredits())
            : "");

    // N ECTS do 2 Ciclo concludos at ao fim do ano lectivo
    // anterior ao que se referem os dados
    final CycleCurriculumGroup secondCycleCurriculumGroup = lastStudentCurricularPlan.getRoot()
            .getCycleCurriculumGroup(CycleType.SECOND_CYCLE);
    row.setCell(secondCycleCurriculumGroup != null && !secondCycleCurriculumGroup.isExternal()
            ? printBigDecimal(secondCycleCurriculumGroup.getCurriculum(executionYear).getSumEctsCredits())
            : "");

    // N ECTS do 2 Ciclo Extra primeiro ciclo concludos at ao fim do ano
    // lectivo anterior ao que se referem os dados
    Double extraFirstCycleEcts = 0d;
    for (final CycleCurriculumGroup cycleCurriculumGroup : lastStudentCurricularPlan
            .getExternalCurriculumGroups()) {
        for (final CurriculumLine curriculumLine : cycleCurriculumGroup.getAllCurriculumLines()) {
            if (!curriculumLine.getExecutionYear().isAfter(executionYear.getPreviousExecutionYear())) {
                extraFirstCycleEcts += curriculumLine
                        .getCreditsConcluded(executionYear.getPreviousExecutionYear());
            }
        }
    }
    row.setCell(printDouble(extraFirstCycleEcts));

    // N ECTS Extracurriculares concludos at ao fim do ano lectivo
    // anterior que ao se referem os dados
    Double extraCurricularEcts = 0d;
    Double allExtraCurricularEcts = 0d;
    if (extraCurriculumGroup != null) {
        for (final CurriculumLine curriculumLine : extraCurriculumGroup.getAllCurriculumLines()) {
            if (curriculumLine.isApproved() && curriculumLine.hasExecutionPeriod()
                    && !curriculumLine.getExecutionYear().isAfter(executionYear.getPreviousExecutionYear())) {
                extraCurricularEcts += curriculumLine.getEctsCreditsForCurriculum().doubleValue();
            }
            if (curriculumLine.hasExecutionPeriod() && curriculumLine.getExecutionYear() == executionYear) {
                allExtraCurricularEcts += curriculumLine.getEctsCreditsForCurriculum().doubleValue();
            }
        }
    }
    row.setCell(printDouble(extraCurricularEcts));

    // N ECTS Propedeutic concludos at ao fim do ano lectivo
    // anterior que ao se referem os dados
    Double propaedeuticEcts = 0d;
    Double allPropaedeuticEcts = 0d;
    if (lastStudentCurricularPlan.getPropaedeuticCurriculumGroup() != null) {
        for (final CurriculumLine curriculumLine : lastStudentCurricularPlan.getPropaedeuticCurriculumGroup()
                .getAllCurriculumLines()) {
            if (curriculumLine.isApproved() && curriculumLine.hasExecutionPeriod()
                    && !curriculumLine.getExecutionYear().isAfter(executionYear.getPreviousExecutionYear())) {
                propaedeuticEcts += curriculumLine.getEctsCreditsForCurriculum().doubleValue();
            }
            if (curriculumLine.hasExecutionPeriod() && curriculumLine.getExecutionYear() == executionYear) {
                allPropaedeuticEcts += curriculumLine.getEctsCreditsForCurriculum().doubleValue();
            }
        }
    }
    row.setCell(printDouble(propaedeuticEcts));

    // N ECTS inscritos em unidades curriculares propeduticas e em
    // extra-curriculares
    row.setCell(printDouble(allPropaedeuticEcts + allExtraCurricularEcts));

    // N ECTS equivalncia/substituio/dispensa
    row.setCell(printDouble(totalCreditsDismissed));

    // Tem situao de propinas no lectivo dos dados
    row.setCell(String.valueOf(lastStudentCurricularPlan.hasAnyGratuityEventFor(executionYear)));

    return row;
}

From source file:net.sourceforge.fenixedu.presentationTier.renderers.converters.YearMonthDayConverter.java

License:Open Source License

@Override
public String deserialize(Object object) {
    YearMonthDay date = (YearMonthDay) object;
    if (date != null) {
        return date.toString("yyyy-MM-dd");
    }/*from  www .  j a  v a 2 s  .co m*/
    return "";
}

From source file:net.sourceforge.fenixedu.presentationTier.servlets.filters.ProcessCandidacyPrintAllDocumentsFilter.java

License:Open Source License

@SuppressWarnings("unchecked")
private ByteArrayOutputStream createAcademicAdminProcessSheet(Person person) throws JRException {
    InputStream istream = getClass().getResourceAsStream(ACADEMIC_ADMIN_SHEET_REPORT_PATH);
    JasperReport report = (JasperReport) JRLoader.loadObject(istream);

    @SuppressWarnings("rawtypes")
    HashMap map = new HashMap();

    try {//from  w  w w.jav  a  2s.c  om
        final Student student = person.getStudent();
        final Registration registration = findRegistration(student);

        map.put("executionYear", ExecutionYear.readCurrentExecutionYear().getYear());
        if (registration != null) {
            map.put("course", registration.getDegree().getNameI18N().toString());
        }
        map.put("studentNumber", student.getNumber().toString());
        map.put("fullName", person.getName());

        try {
            map.put("photo",
                    new ByteArrayInputStream(person.getPersonalPhotoEvenIfPending().getDefaultAvatar()));
        } catch (Exception e) {
            // nothing; print everything else
        }

        map.put("sex", BundleUtil.getString(Bundle.ENUMERATION, person.getGender().name()));
        map.put("maritalStatus", person.getMaritalStatus().getPresentationName());
        map.put("profession", person.getProfession());
        map.put("idDocType", person.getIdDocumentType().getLocalizedName());
        map.put("idDocNumber", person.getDocumentIdNumber());

        YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
        if (emissionDate != null) {
            map.put("idDocEmissionDate", emissionDate.toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
        }

        map.put("idDocExpirationDate", person.getExpirationDateOfDocumentIdYearMonthDay()
                .toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
        map.put("idDocEmissionLocation", person.getEmissionLocationOfDocumentId());

        String nif = person.getSocialSecurityNumber();
        if (nif != null) {
            map.put("NIF", nif);
        }

        map.put("birthDate",
                person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
        map.put("nationality", person.getCountryOfBirth().getCountryNationality().toString());
        map.put("parishOfBirth", person.getParishOfBirth());
        map.put("districtSubdivisionOfBirth", person.getDistrictSubdivisionOfBirth());
        map.put("districtOfBirth", person.getDistrictOfBirth());
        map.put("countryOfBirth", person.getCountryOfBirth().getName());
        map.put("fathersName", person.getNameOfFather());
        map.put("mothersName", person.getNameOfMother());
        map.put("address", person.getAddress());
        map.put("postalCode", person.getPostalCode());
        map.put("locality", person.getAreaOfAreaCode());
        map.put("cellphoneNumber", person.getDefaultMobilePhoneNumber());
        map.put("telephoneNumber", person.getDefaultPhoneNumber());
        map.put("emailAddress", getMail(person));
        map.put("currentDate", new java.text.SimpleDateFormat("'Lisboa, 'dd' de 'MMMM' de 'yyyy",
                new java.util.Locale("PT", "pt")).format(new java.util.Date()));
    } catch (NullPointerException e) {
        // nothing; will cause printing of incomplete form
        // better than no form at all
    }

    JasperPrint print = JasperFillManager.fillReport(report, map);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    JasperExportManager.exportReportToPdfStream(print, output);
    return output;
}

From source file:net.sourceforge.fenixedu.presentationTier.TagLib.GanttDiagramTagLib.java

License:Open Source License

private void generateHeaders(StringBuilder builder) throws JspException {

    switch (getViewTypeEnum()) {

    case WEEKLY://  www  . ja va2 s.  c o  m

        builder.append("<tr>");
        builder.append("<th style=\"width: 15em;\" rowspan=\"4\">")
                .append(getMessage("label.ganttDiagram.event")).append("</th>");
        for (Integer year : getGanttDiagramObject().getYearsView().keySet()) {
            builder.append("<th colspan=\"").append(getGanttDiagramObject().getYearsView().get(year))
                    .append("\">").append(year).append("</th>");
        }
        if (isShowPeriod()) {
            builder.append("<th style=\"width: 20em;\" rowspan=\"4\">")
                    .append(getMessage("label.ganttDiagram.period")).append("</th>");
        }
        if (isShowObservations()) {
            builder.append("<th rowspan=\"4\">").append(getMessage("label.ganttDiagram.observations"))
                    .append("</th>");
        }
        builder.append("</tr>");

        builder.append("<tr>");
        if (!StringUtils.isEmpty(getMonthlyViewUrl())) {
            String monthlyViewUrl_ = getRequest().getContextPath() + getMonthlyViewUrl() + "&amp;"
                    + getFirstDayParameter() + "=";
            for (YearMonthDay month : getGanttDiagramObject().getMonthsView().keySet()) {
                builder.append("<th colspan=\"").append(getGanttDiagramObject().getMonthsView().get(month))
                        .append("\">").append("<a href=\"").append(monthlyViewUrl_)
                        .append(month.toString("ddMMyyyy")).append("\">")
                        .append(month.toString("MMM", getGanttDiagramObject().getLocale())).append("</a>")
                        .append("</th>");
            }
        } else {
            for (YearMonthDay month : getGanttDiagramObject().getMonthsView().keySet()) {
                builder.append("<th colspan=\"").append(getGanttDiagramObject().getMonthsView().get(month))
                        .append("\">").append(month.toString("MMM", getGanttDiagramObject().getLocale()))
                        .append("</th>");
            }
        }
        builder.append("</tr>");

        builder.append("<tr>");
        for (DateTime day : getGanttDiagramObject().getDays()) {
            builder.append("<th>").append(day.toString("E", getGanttDiagramObject().getLocale()))
                    .append("</th>");
        }
        builder.append("</tr>");

        builder.append("<tr>");
        if (!StringUtils.isEmpty(getDailyViewUrl())) {
            String dailyViewUrl_ = getRequest().getContextPath() + getDailyViewUrl() + "&amp;"
                    + getFirstDayParameter() + "=";
            for (DateTime day : getGanttDiagramObject().getDays()) {
                builder.append("<th>").append("<a href=\"").append(dailyViewUrl_)
                        .append(day.toString("ddMMyyyy")).append("\">").append(day.getDayOfMonth())
                        .append("</a>").append("</th>");
            }
        } else {
            for (DateTime day : getGanttDiagramObject().getDays()) {
                builder.append("<th>").append(day.getDayOfMonth()).append("</th>");
            }
        }

        builder.append("</tr>");
        break;

    case MONTHLY:

        builder.append("<tr>");
        builder.append("<th style=\"width: 15em;\" rowspan=\"2\">")
                .append(getMessage("label.ganttDiagram.event")).append("</th>");
        for (YearMonthDay month : getGanttDiagramObject().getMonthsView().keySet()) {
            builder.append("<th colspan=\"").append(getGanttDiagramObject().getMonthsView().get(month))
                    .append("\">").append(month.toString("MMM yyyy", getGanttDiagramObject().getLocale()))
                    .append("</th>");
        }
        if (isShowPeriod()) {
            builder.append("<th style=\"width: 20em;\" rowspan=\"2\">")
                    .append(getMessage("label.ganttDiagram.period")).append("</th>");
        }
        if (isShowObservations()) {
            builder.append("<th rowspan=\"2\">").append(getMessage("label.ganttDiagram.observations"))
                    .append("</th>");
        }
        builder.append("</tr>");

        builder.append("<tr>");
        if (!StringUtils.isEmpty(getDailyViewUrl())) {
            String dailyViewUrl_ = getRequest().getContextPath() + getDailyViewUrl() + "&amp;"
                    + getFirstDayParameter() + "=";
            for (DateTime day : getGanttDiagramObject().getDays()) {
                builder.append("<th>").append("<a href=\"").append(dailyViewUrl_)
                        .append(day.toString("ddMMyyyy")).append("\">").append(day.getDayOfMonth())
                        .append("</a>").append("</th>");
            }
        } else {
            for (DateTime day : getGanttDiagramObject().getDays()) {
                builder.append("<th>").append(day.getDayOfMonth()).append("</th>");
            }
        }

        builder.append("</tr>");
        break;

    case DAILY:

        builder.append("<tr>");
        builder.append("<th style=\"width: 15em;\">").append(getMessage("label.ganttDiagram.event"))
                .append("</th>");
        builder.append("<th>")
                .append(getGanttDiagramObject().getFirstInstant().toString("E",
                        getGanttDiagramObject().getLocale()))
                .append(", ").append(getGanttDiagramObject().getFirstInstant().getDayOfMonth()).append(" ");

        if (!StringUtils.isEmpty(getMonthlyViewUrl())) {
            String monthlyViewUrl_ = getRequest().getContextPath() + getMonthlyViewUrl() + "&amp;"
                    + getFirstDayParameter() + "=";
            builder.append("<a href=\"").append(monthlyViewUrl_)
                    .append(getGanttDiagramObject().getFirstInstant().toString("ddMMyyyy")).append("\">")
                    .append(getGanttDiagramObject().getFirstInstant().toString("MMM",
                            getGanttDiagramObject().getLocale()))
                    .append("</a>");
        } else {
            builder.append(getGanttDiagramObject().getFirstInstant().toString("MMM",
                    getGanttDiagramObject().getLocale()));
        }

        builder.append(" ").append(getGanttDiagramObject().getFirstInstant().getYear());

        if (!StringUtils.isEmpty(getWeeklyViewUrl())) {
            String weeklyViewUrl_ = getRequest().getContextPath() + getWeeklyViewUrl() + "&amp;"
                    + getFirstDayParameter() + "=";
            builder.append(" (<a href=\"").append(weeklyViewUrl_)
                    .append(getGanttDiagramObject().getFirstInstant().toString("ddMMyyyy")).append("\">");
            builder.append(getMessage("label.ganttDiagram.week"))
                    .append(getGanttDiagramObject().getFirstInstant().getWeekOfWeekyear()).append(")</a>");
        }

        builder.append("</th>");
        if (isShowPeriod()) {
            builder.append("<th style=\"width: 20em;\">").append(getMessage("label.ganttDiagram.period"))
                    .append("</th>");
        }
        if (isShowObservations()) {
            builder.append("<th>").append(getMessage("label.ganttDiagram.observations")).append("</th>");
        }
        builder.append("</tr>");
        break;

    case TOTAL:

        builder.append("<tr>");
        builder.append("<th style=\"width: 15em;\" rowspan=\"2\">")
                .append(getMessage("label.ganttDiagram.event")).append("</th>");
        for (Integer year : getGanttDiagramObject().getYearsView().keySet()) {
            builder.append("<th colspan=\"").append(getGanttDiagramObject().getYearsView().get(year))
                    .append("\">").append(year).append("</th>");
        }
        if (isShowPeriod()) {
            builder.append("<th style=\"width: 20em;\" rowspan=\"2\">")
                    .append(getMessage("label.ganttDiagram.period")).append("</th>");
        }
        if (isShowObservations()) {
            builder.append("<th rowspan=\"2\">").append(getMessage("label.ganttDiagram.observations"))
                    .append("</th>");
        }
        builder.append("</tr>");

        builder.append("<tr>");
        for (DateTime month : getGanttDiagramObject().getMonths()) {
            builder.append("<th>").append(month.toString("MMM", getGanttDiagramObject().getLocale()))
                    .append("</th>");
        }
        builder.append("</tr>");
        break;

    case MONTHLY_TOTAL:

        builder.append("<tr>");
        builder.append("<th style=\"width: 15em;\">").append(getMessage("label.ganttDiagram.event"))
                .append("</th>");
        builder.append("<th>")
                .append(getGanttDiagramObject().getFirstInstant().toString("MMM",
                        getGanttDiagramObject().getLocale()))
                .append(" ").append(getGanttDiagramObject().getFirstInstant().getYear()).append("</th>");
        if (isShowPeriod()) {
            builder.append("<th style=\"width: 20em;\">").append(getMessage("label.ganttDiagram.period"))
                    .append("</th>");
        }
        if (isShowObservations()) {
            builder.append("<th>").append(getMessage("label.ganttDiagram.observations")).append("</th>");
        }
        builder.append("</tr>");
        break;

    case YEAR_DAILY:

        builder.append("<tr>");
        builder.append("<th rowspan=\"2\">").append(getMessage("label.ganttDiagram.event")).append("</th>");
        for (Integer year : getGanttDiagramObject().getYearsView().keySet()) {
            builder.append("<th colspan=\"").append(getGanttDiagramObject().getYearsView().get(year))
                    .append("\">").append(year).append("</th>");
        }
        if (isShowPeriod()) {
            builder.append("<th style=\"width: 20em;\" rowspan=\"2\">")
                    .append(getMessage("label.ganttDiagram.period")).append("</th>");
        }
        if (isShowObservations()) {
            builder.append("<th rowspan=\"2\">").append(getMessage("label.ganttDiagram.observations"))
                    .append("</th>");
        }
        builder.append("</tr>");

        builder.append("<tr>");
        if (!StringUtils.isEmpty(getDailyViewUrl())) {
            String dailyViewUrl_ = getRequest().getContextPath() + getDailyViewUrl() + "&amp;"
                    + getFirstDayParameter() + "=";
            for (DateTime day : getGanttDiagramObject().getDays()) {
                builder.append("<th>").append("<a href=\"").append(dailyViewUrl_)
                        .append(day.toString("ddMMyyyy")).append("\">").append(day.getDayOfMonth())
                        .append("</a>").append("</th>");
            }
        } else {
            for (DateTime day : getGanttDiagramObject().getDays()) {
                builder.append("<th>").append(day.getDayOfMonth()).append("</th>");
            }
        }

        builder.append("</tr>");
        break;

    default:
        break;
    }
}

From source file:org.fenixedu.academic.domain.reports.RaidesCommonReportFieldsWrapper.java

License:Open Source License

public static Row reportRaidesFields(final Spreadsheet sheet, final Registration registration,
        StudentCurricularPlan studentCurricularPlan, List<Registration> registrationPath,
        ExecutionYear executionYear, final CycleType cycleType, final boolean concluded,
        final YearMonthDay conclusionDate, BigDecimal average, boolean graduation) {

    final Row row = sheet.addRow();
    final Person graduate = registration.getPerson();
    //List<Registration> registrationPath = getFullRegistrationPath(registration);
    Registration sourceRegistration = registrationPath.iterator().next();
    final PersonalInformationBean personalInformationBean = registration
            .getPersonalInformationBean(executionYear);

    // Ciclo//from   w  w w  . j a  va2  s. c om
    row.setCell(cycleType.getDescription());

    // Concludo
    row.setCell(String.valueOf(concluded));

    // Mdia do Ciclo
    if (graduation) {
        row.setCell(concluded ? printBigDecimal(average.setScale(0, BigDecimal.ROUND_HALF_EVEN))
                : printBigDecimal(average));
    } else {
        row.setCell(
                concluded ? studentCurricularPlan.getCycle(cycleType).getCurriculum().getRawGrade().getValue()
                        : "n/a");
    }

    // Data de Concluso
    row.setCell(conclusionDate != null ? conclusionDate.toString("dd-MM-yyyy") : "");

    // Data de Incio
    row.setCell(registration.getStartDate() != null ? registration.getStartDate().toString("dd-MM-yyyy") : "");

    // N de aluno
    row.setCell(registration.getNumber());

    // Nome de Utilizador
    row.setCell(registration.getPerson().getUsername());

    // Tipo Identificao
    row.setCell(graduate.getIdDocumentType().getLocalizedName());

    // N de Identificao
    row.setCell(graduate.getDocumentIdNumber());

    // Dgitos de Controlo
    row.setCell(graduate.getIdentificationDocumentExtraDigitValue());

    // Verso Doc. Identificao
    row.setCell(graduate.getIdentificationDocumentSeriesNumberValue());

    // Nome
    row.setCell(registration.getName());

    // Sexo
    row.setCell(graduate.getGender().toString());

    // Data de Nascimento
    row.setCell(graduate.getDateOfBirthYearMonthDay() != null
            ? graduate.getDateOfBirthYearMonthDay().toString("dd-MM-yyyy")
            : "n/a");

    // Pas de Nascimento
    row.setCell(graduate.getCountryOfBirth() != null ? graduate.getCountryOfBirth().getName() : "n/a");

    // Pas de Nacionalidade
    row.setCell(graduate.getCountry() != null ? graduate.getCountry().getName() : "n/a");

    // Tipo Curso
    row.setCell(registration.getDegreeType().getName().getContent());

    // Nome Curso
    row.setCell(registration.getDegree().getNameI18N().getContent());

    // Sigla Curso
    row.setCell(registration.getDegree().getSigla());

    // Ramos do currculo do aluno
    final StringBuilder majorBranches = new StringBuilder();
    final StringBuilder minorBranches = new StringBuilder();
    for (final BranchCurriculumGroup group : studentCurricularPlan.getBranchCurriculumGroups()) {
        if (group.isMajor()) {
            majorBranches.append(group.getName().getContent()).append(",");
        } else if (group.isMinor()) {
            minorBranches.append(group.getName().getContent()).append(",");
        }
    }

    // Ramo Principal
    if (majorBranches.length() > 0) {
        row.setCell(majorBranches.deleteCharAt(majorBranches.length() - 1).toString());
    } else {
        row.setCell("");
    }

    // Ramo Secundro
    if (minorBranches.length() > 0) {
        row.setCell(minorBranches.deleteCharAt(minorBranches.length() - 1).toString());
    } else {
        row.setCell("");
    }

    // Ano Curricular
    row.setCell(registration.getCurricularYear(executionYear));

    // Ano de Ingresso no Curso Actual
    row.setCell(sourceRegistration.getStartExecutionYear().getName());

    // N de anos lectivos de inscrio no Curso actual
    int numberOfEnrolmentYears = 0;
    for (Registration current : registrationPath) {
        numberOfEnrolmentYears += current.getNumberOfYearsEnrolledUntil(executionYear);
    }
    row.setCell(numberOfEnrolmentYears);

    // ltimo ano em que esteve inscrito
    row.setCell(registration.getLastEnrolmentExecutionYear() != null
            ? registration.getLastEnrolmentExecutionYear().getName()
            : "");

    // Regime de frequncia curso: Tempo integral/Tempo Parcial
    row.setCell(registration.getRegimeType(executionYear) != null
            ? registration.getRegimeType(executionYear).getName()
            : "");

    // Tipo de Aluno (AFA, AM, ERASMUS, etc)
    row.setCell(
            registration.getRegistrationProtocol() != null ? registration.getRegistrationProtocol().getCode()
                    : "");

    // Regime de Ingresso no Curso Actual (cdigo)
    IngressionType ingressionType = sourceRegistration.getIngressionType();
    if (ingressionType == null && sourceRegistration.getStudentCandidacy() != null) {
        ingressionType = sourceRegistration.getStudentCandidacy().getIngressionType();
    }
    row.setCell(ingressionType != null ? ingressionType.getCode() : "");

    // Regime de Ingresso no Curso Actual (designao)
    row.setCell(ingressionType != null ? ingressionType.getDescription().getContent() : "");

    // estabelecimento do grau preced.: Instituio onde esteve
    // inscrito mas no obteve grau, (e.g: transferencias, mudanas de
    // curso...)
    row.setCell(personalInformationBean.getPrecedentInstitution() != null
            ? personalInformationBean.getPrecedentInstitution().getName()
            : "");
    // curso grau preced.
    row.setCell(personalInformationBean.getPrecedentDegreeDesignation() != null
            ? personalInformationBean.getPrecedentDegreeDesignation()
            : "");

    // estabelec. curso habl anterior compl (se o aluno ingressou por uma via
    // diferente CNA, e deve ser IST caso o aluno tenha estado matriculado noutro curso do IST)
    row.setCell(personalInformationBean.getInstitution() != null
            ? personalInformationBean.getInstitution().getName()
            : "");

    // curso habl anterior compl (se o aluno ingressou por uma via diferente CNA, e
    // deve ser IST caso o aluno tenha estado matriculado noutro curso do IST)
    row.setCell(personalInformationBean.getDegreeDesignation());

    // n inscries no curso preced. (conta uma por cada ano)
    row.setCell(personalInformationBean.getNumberOfPreviousYearEnrolmentsInPrecedentDegree() != null
            ? personalInformationBean.getNumberOfPreviousYearEnrolmentsInPrecedentDegree().toString()
            : "");

    // Nota de Ingresso
    Double entryGrade = null;
    if (registration.getStudentCandidacy() != null) {
        entryGrade = registration.getStudentCandidacy().getEntryGrade();
    }

    row.setCell(printDouble(entryGrade));

    // Opo de Ingresso
    Integer placingOption = null;
    if (registration.getStudentCandidacy() != null) {
        placingOption = registration.getStudentCandidacy().getPlacingOption();
    }

    row.setCell(placingOption);

    // Estado Civil
    row.setCell(personalInformationBean.getMaritalStatus() != null
            ? personalInformationBean.getMaritalStatus().toString()
            : registration.getPerson().getMaritalStatus().toString());

    // Pas de Residncia Permanente
    if (personalInformationBean.getCountryOfResidence() != null) {
        row.setCell(personalInformationBean.getCountryOfResidence().getName());
    } else {
        row.setCell(registration.getStudent().getPerson().getCountryOfResidence() != null
                ? registration.getStudent().getPerson().getCountryOfResidence().getName()
                : "");
    }

    // Distrito de Residncia Permanente
    if (personalInformationBean.getDistrictSubdivisionOfResidence() != null) {
        row.setCell(personalInformationBean.getDistrictSubdivisionOfResidence().getDistrict().getName());
    } else {
        row.setCell(registration.getStudent().getPerson().getDistrictOfResidence());
    }

    // Concelho de Residncia Permanente
    if (personalInformationBean.getDistrictSubdivisionOfResidence() != null) {
        row.setCell(personalInformationBean.getDistrictSubdivisionOfResidence().getName());
    } else {
        row.setCell(registration.getStudent().getPerson().getDistrictSubdivisionOfResidence());
    }

    // Deslocado da Residncia Permanente
    if (personalInformationBean.getDislocatedFromPermanentResidence() != null) {
        row.setCell(personalInformationBean.getDislocatedFromPermanentResidence().toString());
    } else {
        row.setCell("");
    }

    // Nvel de Escolaridade do Pai
    if (personalInformationBean.getFatherSchoolLevel() != null) {
        row.setCell(personalInformationBean.getFatherSchoolLevel().getName());
    } else {
        row.setCell("");
    }

    // Nvel de Escolaridade da Me
    if (personalInformationBean.getMotherSchoolLevel() != null) {
        row.setCell(personalInformationBean.getMotherSchoolLevel().getName());
    } else {
        row.setCell("");
    }

    // Condio perante a situao na profisso/Ocupao do
    // Pai
    if (personalInformationBean.getFatherProfessionalCondition() != null) {
        row.setCell(personalInformationBean.getFatherProfessionalCondition().getName());
    } else {
        row.setCell("");
    }

    // Condio perante a situao na profisso/Ocupao da
    // Me
    if (personalInformationBean.getMotherProfessionalCondition() != null) {
        row.setCell(personalInformationBean.getMotherProfessionalCondition().getName());
    } else {
        row.setCell("");
    }

    // Profisso do Pai
    if (personalInformationBean.getFatherProfessionType() != null) {
        row.setCell(personalInformationBean.getFatherProfessionType().getName());
    } else {
        row.setCell("");
    }

    // Profisso da Me
    if (personalInformationBean.getMotherProfessionType() != null) {
        row.setCell(personalInformationBean.getMotherProfessionType().getName());
    } else {
        row.setCell("");
    }

    // Profisso do Aluno
    if (personalInformationBean.getProfessionType() != null) {
        row.setCell(personalInformationBean.getProfessionType().getName());
    } else {
        row.setCell("");
    }

    // Data preenchimento dados RAIDES
    if (personalInformationBean.getLastModifiedDate() != null) {
        DateTime dateTime = personalInformationBean.getLastModifiedDate();
        row.setCell(dateTime.getYear() + "-" + dateTime.getMonthOfYear() + "-" + dateTime.getDayOfMonth());
    } else {
        row.setCell("");
    }

    // Estatuto de Trabalhador Estudante introduzido pelo aluno
    if (personalInformationBean.getProfessionalCondition() != null) {
        row.setCell(personalInformationBean.getProfessionalCondition().getName());
    } else {
        row.setCell("");
    }

    // Estatuto de Trabalhador Estudante 1 semestre do ano a que se
    // referem
    // os dados
    boolean working1Found = false;
    for (StudentStatute statute : registration.getStudent().getStudentStatutesSet()) {
        if (statute.getType().isWorkingStudentStatute()
                && statute.isValidInExecutionPeriod(executionYear.getFirstExecutionPeriod())) {
            working1Found = true;
            break;
        }
    }
    row.setCell(String.valueOf(working1Found));

    // Estatuto de Trabalhador Estudante 1 semestre do ano a que se
    // referem
    // os dados
    boolean working2Found = false;
    for (StudentStatute statute : registration.getStudent().getStudentStatutesSet()) {
        if (statute.getType().isWorkingStudentStatute()
                && statute.isValidInExecutionPeriod(executionYear.getLastExecutionPeriod())) {
            working2Found = true;
            break;
        }
    }
    row.setCell(String.valueOf(working2Found));

    // Bolseiro (info. RAIDES)
    if (personalInformationBean.getGrantOwnerType() != null) {
        row.setCell(personalInformationBean.getGrantOwnerType().getName());
    } else {
        row.setCell("");
    }

    // Instituio que atribuiu a bolsa
    if (personalInformationBean.getGrantOwnerType() != null && personalInformationBean.getGrantOwnerType()
            .equals(GrantOwnerType.OTHER_INSTITUTION_GRANT_OWNER)) {
        row.setCell(personalInformationBean.getGrantOwnerProviderName());
    } else {
        row.setCell("");
    }

    // Bolseiro (info. oficial)
    boolean sasFound = false;
    for (StudentStatute statute : registration.getStudent().getStudentStatutesSet()) {
        if (statute.getType().isGrantOwnerStatute()
                && statute.isValidInExecutionPeriod(executionYear.getFirstExecutionPeriod())) {
            sasFound = true;
            break;
        }
    }
    row.setCell(String.valueOf(sasFound));

    // Grau Precedente
    row.setCell(personalInformationBean.getPrecedentSchoolLevel() != null
            ? personalInformationBean.getPrecedentSchoolLevel().getName()
            : "");

    // Outro Grau Precedente
    row.setCell(personalInformationBean.getOtherPrecedentSchoolLevel());

    // grau da habl anterior compl
    row.setCell(personalInformationBean.getSchoolLevel() != null
            ? personalInformationBean.getSchoolLevel().getName()
            : "");

    // Codigo do grau habl anterior
    DegreeDesignation designation = DegreeDesignation.readByNameAndSchoolLevel(
            personalInformationBean.getDegreeDesignation(), personalInformationBean.getPrecedentSchoolLevel());
    row.setCell(designation != null ? designation.getDegreeClassification().getCode() : "");

    // Outro grau da habl anterior compl
    row.setCell(personalInformationBean.getOtherSchoolLevel());

    // Pas de Habilitao Anterior ao Curso Actual
    row.setCell(personalInformationBean.getCountryWhereFinishedPreviousCompleteDegree() != null
            ? personalInformationBean.getCountryWhereFinishedPreviousCompleteDegree().getName()
            : "");

    // Pas de Habilitao do 12 ano ou equivalente
    row.setCell(personalInformationBean.getCountryWhereFinishedHighSchoolLevel() != null
            ? personalInformationBean.getCountryWhereFinishedHighSchoolLevel().getName()
            : "");

    // Ano de concluso da habilitao anterior
    row.setCell(personalInformationBean.getConclusionYear());

    // Nota de concluso da habilitao anterior
    row.setCell(
            personalInformationBean.getConclusionGrade() != null ? personalInformationBean.getConclusionGrade()
                    : "");

    MobilityAgreement mobilityAgreement = null;
    ExecutionInterval chosenCandidacyInterval = null;
    //getting the last mobility program done
    for (OutboundMobilityCandidacySubmission outboundCandidacySubmission : registration
            .getOutboundMobilityCandidacySubmissionSet()) {
        if (outboundCandidacySubmission.getSelectedCandidacy() != null
                && outboundCandidacySubmission.getSelectedCandidacy().getSelected()) {
            ExecutionInterval candidacyInterval = outboundCandidacySubmission
                    .getOutboundMobilityCandidacyPeriod().getExecutionInterval();
            //the candidacies are made in the previous year
            if (candidacyInterval.getAcademicInterval().isBefore(executionYear.getAcademicInterval())) {
                if (mobilityAgreement != null) {
                    if (!candidacyInterval.getAcademicInterval()
                            .isAfter(chosenCandidacyInterval.getAcademicInterval())) {
                        continue;
                    }
                }
                mobilityAgreement = outboundCandidacySubmission.getSelectedCandidacy()
                        .getOutboundMobilityCandidacyContest().getMobilityAgreement();
                chosenCandidacyInterval = candidacyInterval;
            }
        }
    }
    // Programa de mobilidade
    row.setCell(mobilityAgreement != null ? mobilityAgreement.getMobilityProgram().getName().getContent() : "");

    // Pas de mobilidade
    row.setCell(mobilityAgreement != null ? mobilityAgreement.getUniversityUnit().getCountry().getName() : "");

    // Durao do programa de mobilidade
    row.setCell(personalInformationBean.getMobilityProgramDuration() != null ? BundleUtil
            .getString(Bundle.ENUMERATION, personalInformationBean.getMobilityProgramDuration().name()) : "");

    // Tipo de Estabelecimento Frequentado no Ensino Secundrio
    if (personalInformationBean.getHighSchoolType() != null) {
        row.setCell(personalInformationBean.getHighSchoolType().getName());
    } else {
        row.setCell("");
    }

    int totalEnrolmentsInPreviousYear = 0;
    int totalEnrolmentsApprovedInPreviousYear = 0;
    //int totalEnrolmentsInFirstSemester = 0;
    double totalEctsConcludedUntilPreviousYear = 0d;
    for (final CycleCurriculumGroup cycleCurriculumGroup : studentCurricularPlan
            .getInternalCycleCurriculumGrops()) {

        totalEctsConcludedUntilPreviousYear += cycleCurriculumGroup
                .getCreditsConcluded(executionYear.getPreviousExecutionYear());

        totalEnrolmentsInPreviousYear += cycleCurriculumGroup
                .getEnrolmentsBy(executionYear.getPreviousExecutionYear()).size();

        for (final Enrolment enrolment : cycleCurriculumGroup
                .getEnrolmentsBy(executionYear.getPreviousExecutionYear())) {
            if (enrolment.isApproved()) {
                totalEnrolmentsApprovedInPreviousYear++;
            }
        }

        //       totalEnrolmentsInFirstSemester += cycleCurriculumGroup.getEnrolmentsBy(executionYear.getFirstExecutionPeriod())
        //          .size();
    }

    // Total de ECTS inscritos no total do ano
    double totalCreditsEnrolled = 0d;
    for (Enrolment enrollment : studentCurricularPlan.getEnrolmentsByExecutionYear(executionYear)) {
        totalCreditsEnrolled += enrollment.getEctsCredits();
    }
    row.setCell(printDouble(totalCreditsEnrolled));

    // Total de ECTS concludos at ao fim do ano lectivo anterior ao
    // que se
    // referem os dados (neste caso at ao fim de 2007/08) no curso actual
    double totalCreditsDismissed = 0d;
    for (Credits credits : studentCurricularPlan.getCreditsSet()) {
        if (credits.isEquivalence()) {
            totalCreditsDismissed += credits.getEnrolmentsEcts();
        }
    }
    row.setCell(printDouble(totalEctsConcludedUntilPreviousYear));

    // N de Disciplinas Inscritos no ano lectivo anterior ao que se
    // referem
    // os dados
    row.setCell(totalEnrolmentsInPreviousYear);

    // N de Disciplinas Aprovadas no ano lectivo anterior ao que se
    // referem
    // os dados
    row.setCell(totalEnrolmentsApprovedInPreviousYear);

    // N de Inscries Externas no ano a que se referem os dados
    ExtraCurriculumGroup extraCurriculumGroup = studentCurricularPlan.getExtraCurriculumGroup();
    int extraCurricularEnrolmentsCount = extraCurriculumGroup != null
            ? extraCurriculumGroup.getEnrolmentsBy(executionYear).size()
            : 0;

    for (final CycleCurriculumGroup cycleCurriculumGroup : studentCurricularPlan
            .getExternalCurriculumGroups()) {
        extraCurricularEnrolmentsCount += cycleCurriculumGroup.getEnrolmentsBy(executionYear).size();
    }

    if (studentCurricularPlan.hasPropaedeuticsCurriculumGroup()) {
        extraCurricularEnrolmentsCount += studentCurricularPlan.getPropaedeuticCurriculumGroup()
                .getEnrolmentsBy(executionYear).size();
    }

    row.setCell(extraCurricularEnrolmentsCount);

    // Estados de matrcula
    SortedSet<RegistrationState> states = new TreeSet<RegistrationState>(RegistrationState.DATE_COMPARATOR);
    for (Registration current : registrationPath) {
        states.addAll(current.getRegistrationStatesSet());
    }
    RegistrationState previousYearState = null;
    RegistrationState currentYearState = null;
    for (RegistrationState state : states) {
        if (!state.getStateDate().isAfter(
                executionYear.getPreviousExecutionYear().getEndDateYearMonthDay().toDateTimeAtMidnight())) {
            previousYearState = state;
        }
        if (!state.getStateDate().isAfter(executionYear.getEndDateYearMonthDay().toDateTimeAtMidnight())) {
            currentYearState = state;
        }
    }

    // Estado da matrcula no ano lectivo anterior ao que se referem os
    // dados
    row.setCell(previousYearState != null ? previousYearState.getStateType().getDescription() : "n/a");

    // Estado (da matrcula) no ano a que se referem os dados
    row.setCell(currentYearState != null ? currentYearState.getStateType().getDescription() : "n/a");

    // Data do estado de matrcula
    row.setCell(currentYearState != null ? currentYearState.getStateDate().toString("dd-MM-yyyy") : "n/a");

    // N ECTS do 1 Ciclo concludos at ao fim do ano lectivo
    // anterior ao que se referem os dados
    final CycleCurriculumGroup firstCycleCurriculumGroup = getStudentCurricularPlan(registration,
            CycleType.FIRST_CYCLE).getCycle(CycleType.FIRST_CYCLE);
    row.setCell(firstCycleCurriculumGroup != null
            ? printBigDecimal(firstCycleCurriculumGroup.getCurriculum(executionYear).getSumEctsCredits())
            : "");

    // N ECTS do 2 Ciclo concludos at ao fim do ano lectivo
    // anterior ao que se referem os dados
    final CycleCurriculumGroup secondCycleCurriculumGroup = getStudentCurricularPlan(registration,
            CycleType.SECOND_CYCLE).getCycle(CycleType.SECOND_CYCLE);
    row.setCell(secondCycleCurriculumGroup != null && !secondCycleCurriculumGroup.isExternal()
            ? printBigDecimal(secondCycleCurriculumGroup.getCurriculum(executionYear).getSumEctsCredits())
            : "");

    // N ECTS do 2 Ciclo Extra primeiro ciclo concludos at ao fim do ano
    // lectivo anterior ao que se referem os dados
    Double extraFirstCycleEcts = 0d;
    for (final CycleCurriculumGroup cycleCurriculumGroup : studentCurricularPlan
            .getExternalCurriculumGroups()) {
        for (final CurriculumLine curriculumLine : cycleCurriculumGroup.getAllCurriculumLines()) {
            if (!curriculumLine.getExecutionYear().isAfter(executionYear.getPreviousExecutionYear())) {
                extraFirstCycleEcts += curriculumLine
                        .getCreditsConcluded(executionYear.getPreviousExecutionYear());
            }
        }
    }
    row.setCell(printDouble(extraFirstCycleEcts));

    // N ECTS Extracurriculares concludos at ao fim do ano lectivo
    // anterior que ao se referem os dados
    Double extraCurricularEcts = 0d;
    Double allExtraCurricularEcts = 0d;
    if (extraCurriculumGroup != null) {
        for (final CurriculumLine curriculumLine : extraCurriculumGroup.getAllCurriculumLines()) {
            if (curriculumLine.isApproved() && curriculumLine.hasExecutionPeriod()
                    && !curriculumLine.getExecutionYear().isAfter(executionYear.getPreviousExecutionYear())) {
                extraCurricularEcts += curriculumLine.getEctsCreditsForCurriculum().doubleValue();
            }
            if (curriculumLine.hasExecutionPeriod() && curriculumLine.getExecutionYear() == executionYear) {
                allExtraCurricularEcts += curriculumLine.getEctsCreditsForCurriculum().doubleValue();
            }
        }
    }
    row.setCell(printDouble(extraCurricularEcts));

    // N ECTS Propedeutic concludos at ao fim do ano lectivo
    // anterior que ao se referem os dados
    Double propaedeuticEcts = 0d;
    Double allPropaedeuticEcts = 0d;
    if (studentCurricularPlan.getPropaedeuticCurriculumGroup() != null) {
        for (final CurriculumLine curriculumLine : studentCurricularPlan.getPropaedeuticCurriculumGroup()
                .getAllCurriculumLines()) {
            if (curriculumLine.isApproved() && curriculumLine.hasExecutionPeriod()
                    && !curriculumLine.getExecutionYear().isAfter(executionYear.getPreviousExecutionYear())) {
                propaedeuticEcts += curriculumLine.getEctsCreditsForCurriculum().doubleValue();
            }
            if (curriculumLine.hasExecutionPeriod() && curriculumLine.getExecutionYear() == executionYear) {
                allPropaedeuticEcts += curriculumLine.getEctsCreditsForCurriculum().doubleValue();
            }
        }
    }
    row.setCell(printDouble(propaedeuticEcts));

    // N ECTS inscritos em unidades curriculares propeduticas e em
    // extra-curriculares
    row.setCell(printDouble(allPropaedeuticEcts + allExtraCurricularEcts));

    // N ECTS equivalncia/substituio/dispensa
    row.setCell(printDouble(totalCreditsDismissed));

    // Tem situao de propinas no lectivo dos dados
    row.setCell(String.valueOf(studentCurricularPlan.hasAnyGratuityEventFor(executionYear)));

    return row;
}

From source file:org.fenixedu.academic.servlet.ProcessCandidacyPrintAllDocumentsFilter.java

License:Open Source License

@SuppressWarnings("unchecked")
private byte[] createAcademicAdminProcessSheet(Person person) {
    @SuppressWarnings("rawtypes")
    HashMap map = new HashMap();

    try {/*from  w ww .ja  v  a2  s.c o  m*/
        final Student student = person.getStudent();
        final Registration registration = findRegistration(student);

        map.put("executionYear", ExecutionYear.readCurrentExecutionYear().getYear());
        if (registration != null) {
            map.put("course", registration.getDegree().getNameI18N().toString());
        }
        map.put("studentNumber", student.getNumber().toString());
        map.put("fullName", person.getName());

        try {
            map.put("photo",
                    new ByteArrayInputStream(person.getPersonalPhotoEvenIfPending().getDefaultAvatar()));
        } catch (Exception e) {
            // nothing; print everything else
        }

        map.put("sex", BundleUtil.getString(Bundle.ENUMERATION, person.getGender().name()));
        map.put("maritalStatus", person.getMaritalStatus().getPresentationName());
        map.put("profession", person.getProfession());
        map.put("idDocType", person.getIdDocumentType().getLocalizedName());
        map.put("idDocNumber", person.getDocumentIdNumber());

        YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
        if (emissionDate != null) {
            map.put("idDocEmissionDate", emissionDate.toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
        }

        map.put("idDocExpirationDate", person.getExpirationDateOfDocumentIdYearMonthDay()
                .toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
        map.put("idDocEmissionLocation", person.getEmissionLocationOfDocumentId());

        String nif = person.getSocialSecurityNumber();
        if (nif != null) {
            map.put("NIF", nif);
        }

        map.put("birthDate",
                person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
        map.put("nationality", person.getCountryOfBirth().getCountryNationality().toString());
        map.put("parishOfBirth", person.getParishOfBirth());
        map.put("districtSubdivisionOfBirth", person.getDistrictSubdivisionOfBirth());
        map.put("districtOfBirth", person.getDistrictOfBirth());
        map.put("countryOfBirth", person.getCountryOfBirth().getName());
        map.put("fathersName", person.getNameOfFather());
        map.put("mothersName", person.getNameOfMother());
        map.put("address", person.getAddress());
        map.put("postalCode", person.getPostalCode());
        map.put("locality", person.getAreaOfAreaCode());
        map.put("cellphoneNumber", person.getDefaultMobilePhoneNumber());
        map.put("telephoneNumber", person.getDefaultPhoneNumber());
        map.put("emailAddress", getMail(person));
        map.put("currentDate", new java.text.SimpleDateFormat("'Lisboa, 'dd' de 'MMMM' de 'yyyy",
                new java.util.Locale("PT", "pt")).format(new java.util.Date()));
    } catch (NullPointerException e) {
        // nothing; will cause printing of incomplete form
        // better than no form at all
    }

    return ReportsUtils.generateReport(ACADEMIC_ADMIN_SHEET_REPORT_KEY, map, null).getData();
}

From source file:org.fenixedu.idcards.ui.candidacydocfiller.CGDPdfFiller.java

License:Open Source License

private ByteArrayOutputStream getFilledPdfCGDPersonalInformation(Person person)
        throws IOException, DocumentException {
    InputStream istream = getClass().getResourceAsStream(CGD_PERSONAL_INFORMATION_PDF_PATH);
    PdfReader reader = new PdfReader(istream);
    reader.getAcroForm().remove(PdfName.SIGFLAGS);
    reader.selectPages("1");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, output);
    form = stamper.getAcroFields();/*from  w  ww .  j  ava 2 s . c o  m*/

    setField("T_NomeComp", person.getName());
    setField("T_Email", getMail(person));

    if (person.isFemale()) {
        setField("CB_0_1", "Yes"); // female
    } else {
        setField("CB_0_0", "Yes"); // male
    }

    setField("Cod_data_1",
            person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("yyyy/MM/dd")));

    setField("NIF1", person.getSocialSecurityNumber());
    setField("T_DocIdent", person.getDocumentIdNumber());

    switch (person.getMaritalStatus()) {
    case CIVIL_UNION:
        setField("CB_EstCivil01", MARITAL_STATUS_CIVIL_UNION);
        break;
    case DIVORCED:
        setField("CB_EstCivil01", MARITAL_STATUS_DIVORCED);
        break;
    case MARRIED:
        setField("CB_EstCivil01", "");
        break;
    case SEPARATED:
        setField("CB_EstCivil01", MARITAL_STATUS_SEPARATED);
        break;
    case SINGLE:
        setField("CB_EstCivil01", MARITAL_STATUS_SINGLE);
        break;
    case WIDOWER:
        setField("CB_EstCivil01", MARITAL_STATUS_WIDOWER);
        break;
    }
    YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
    if (emissionDate != null) {
        setField("Cod_data_2", emissionDate.toString(DateTimeFormat.forPattern("yyyy/MM/dd")));
    }

    YearMonthDay expirationDate = person.getExpirationDateOfDocumentIdYearMonthDay();
    if (expirationDate != null) {
        setField("Cod_data_3", expirationDate.toString(DateTimeFormat.forPattern("yyyy/MM/dd")));
    }

    setField("T_NomePai", person.getNameOfFather());
    setField("T_NomeMae", person.getNameOfMother());

    setField("T_NatPais", person.getCountryOfBirth().getName());
    setField("T_Naturali", person.getDistrictOfBirth());
    setField("T_NatConc", person.getDistrictSubdivisionOfBirth());
    setField("T_NatFreg", person.getParishOfBirth());
    setField("T_PaisRes", person.getCountryOfBirth().getCountryNationality().toString());

    setField("T_Morada01", person.getAddress());
    setField("T_Localid01", person.getAreaOfAreaCode());
    setField("T_Telef", person.getDefaultMobilePhoneNumber());

    String postalCode = person.getPostalCode();
    int dashIndex = postalCode.indexOf('-');
    setField("T_CodPos01", postalCode.substring(0, 4));
    String last3Numbers = postalCode.substring(dashIndex + 1, dashIndex + 4);
    setField("T_CodPos03_1", last3Numbers);
    setField("T_Localid02_1", person.getAreaOfAreaCode());

    setField("T_Distrito", person.getDistrictOfResidence());
    setField("T_Conc", person.getDistrictSubdivisionOfResidence());
    setField("T_Freguesia", person.getParishOfResidence());
    setField("T_PaisResid", person.getCountryOfResidence().getName());

    stamper.setFormFlattening(true);
    stamper.close();
    return output;
}