Example usage for org.joda.time DateTime getMonthOfYear

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

Introduction

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

Prototype

public int getMonthOfYear() 

Source Link

Document

Get the month of year field value.

Usage

From source file:org.iexhub.connectors.XdsBRepositoryManager.java

License:Apache License

/**
 * @param contract/*w w w .j  a v a2 s . c  om*/
 * @param xmlContent
 * @param mimeType
 * @param updateDocument
 * @return
 * @throws Exception
 */
public RegistryResponseType provideAndRegisterDocumentSet(Contract contract, byte[] xmlContent, String mimeType,
        boolean updateDocument) throws Exception {
    try {
        UUID previousDocumentUuid = (updateDocument) ? UUID.fromString(contract.getId().getIdPart()) : null;
        UUID newDocumentUuid = UUID.randomUUID();
        //         long hi = entryUuid.getMostSignificantBits();
        //         long lo = entryUuid.getLeastSignificantBits();
        //         byte[] bytes = ByteBuffer.allocate(16).putLong(hi).putLong(lo).array();
        //         BigInteger big = new BigInteger(bytes);
        String documentIdToUse = /*"urn:oid:"
                                 +*/ contract.getIdentifier().getValue(); //"2.25."
        //               + big.toString().replace('-',
        //                     '0');

        ProvideAndRegisterDocumentSetRequestType documentSetRequest = new ProvideAndRegisterDocumentSetRequestType();

        // Create SubmitObjectsRequest...
        SubmitObjectsRequest submitObjectsRequest = new SubmitObjectsRequest();

        //  Create RegistryObjectList...
        RegistryObjectListType registryObjectList = new RegistryObjectListType();

        // Create ExtrinsicObject...
        ExtrinsicObjectType extrinsicObject = new ExtrinsicObjectType();
        extrinsicObject.setId("urn:uuid:" + newDocumentUuid.toString());
        extrinsicObject.setMimeType(mimeType);
        extrinsicObject.setObjectType("urn:uuid:7edca82f-054d-47f2-a032-9b2a5b5186c1");

        // Create creationTime rim:Slot...
        ValueListType valueList = null;
        SlotType1 slot = new SlotType1();
        slot.setName("creationTime");
        valueList = new ValueListType();
        Calendar dateVal = Calendar.getInstance();
        dateVal.setTime(contract.getIssued());
        valueList.getValue()
                .add(new StringBuilder().append(dateVal.get(Calendar.YEAR))
                        .append(String.format("%02d", (dateVal.get(Calendar.MONTH) + 1)))
                        .append(String.format("%02d", dateVal.get(Calendar.DAY_OF_MONTH)))
                        .append(String.format("%02d", dateVal.get(Calendar.HOUR)))
                        .append(String.format("%02d", dateVal.get(Calendar.MINUTE)))
                        .append(String.format("%02d", dateVal.get(Calendar.SECOND))).toString());
        slot.setValueList(valueList);
        extrinsicObject.getSlot().add(slot);

        // Create languageCode rim:Slot...
        slot = new SlotType1();
        slot.setName("languageCode");
        valueList = new ValueListType();
        valueList.getValue().add("en-US");
        slot.setValueList(valueList);
        extrinsicObject.getSlot().add(slot);

        // Create serviceStartTime rim:Slot...
        slot = new SlotType1();
        slot.setName("serviceStartTime");
        valueList = new ValueListType();
        dateVal.setTime(contract.getTermFirstRep().getApplies().getStart());
        valueList.getValue()
                .add(new StringBuilder().append(dateVal.get(Calendar.YEAR))
                        .append(String.format("%02d", (dateVal.get(Calendar.MONTH) + 1)))
                        .append(String.format("%02d", dateVal.get(Calendar.DAY_OF_MONTH)))
                        .append(String.format("%02d", dateVal.get(Calendar.HOUR)))
                        .append(String.format("%02d", dateVal.get(Calendar.MINUTE)))
                        .append(String.format("%02d", dateVal.get(Calendar.SECOND))).toString());
        slot.setValueList(valueList);
        extrinsicObject.getSlot().add(slot);

        // Create serviceStopTime rim:Slot...
        slot = new SlotType1();
        slot.setName("serviceStopTime");
        valueList = new ValueListType();
        dateVal.setTime(contract.getTermFirstRep().getApplies().getEnd());
        valueList.getValue()
                .add(new StringBuilder().append(dateVal.get(Calendar.YEAR))
                        .append(String.format("%02d", (dateVal.get(Calendar.MONTH) + 1)))
                        .append(String.format("%02d", dateVal.get(Calendar.DAY_OF_MONTH)))
                        .append(String.format("%02d", dateVal.get(Calendar.HOUR)))
                        .append(String.format("%02d", dateVal.get(Calendar.MINUTE)))
                        .append(String.format("%02d", dateVal.get(Calendar.SECOND))).toString());
        slot.setValueList(valueList);
        extrinsicObject.getSlot().add(slot);

        // Create sourcePatientId rim:Slot...
        ResourceReferenceDt consentSubjectRef = contract.getSubject().get(0);
        IBaseResource referencedSubject = consentSubjectRef.getResource();
        String referencedId = referencedSubject.getIdElement().getIdPart();
        Patient patient = (getContainedResource(Patient.class, contract.getContained().getContainedResources(),
                referencedId) == null) ? null
                        : (Patient) getContainedResource(Patient.class,
                                contract.getContained().getContainedResources(), referencedId);
        slot = new SlotType1();
        slot.setName("sourcePatientId");
        valueList = new ValueListType();
        String patientId = null;
        patientId = referencedId + "^^^&" + iExHubDomainOid + "&ISO";
        valueList.getValue().add(patientId);
        slot.setValueList(valueList);
        extrinsicObject.getSlot().add(slot);

        // Create sourcePatientInfo rim:Slot...
        if ((patient.getName() != null) && (!patient.getName().isEmpty())) {
            slot = new SlotType1();
            slot.setName("sourcePatientInfo");
            valueList = new ValueListType();
            valueList.getValue().add("PID-3|" + referencedId + "^^^&" + iExHubDomainOid + "&ISO");

            StringBuilder name = new StringBuilder();
            name.append("PID-5|" + ((patient.getName().get(0).getFamilyAsSingleString() != null)
                    ? patient.getName().get(0).getFamilyAsSingleString()
                    : "") + "^");

            name.append(((patient.getName().get(0).getGivenAsSingleString() != null)
                    ? patient.getName().get(0).getGivenAsSingleString()
                    : "") + "^^");

            name.append(((patient.getName().get(0).getPrefixAsSingleString() != null)
                    ? patient.getName().get(0).getPrefixAsSingleString()
                    : "") + "^");

            name.append(((patient.getName().get(0).getSuffixAsSingleString() != null)
                    ? patient.getName().get(0).getSuffixAsSingleString()
                    : ""));

            valueList.getValue().add(name.toString());
        }

        // Birthdate
        dateVal.setTime(patient.getBirthDate());
        valueList.getValue()
                .add(new StringBuilder().append("PID-7|").append(dateVal.get(Calendar.YEAR))
                        .append(String.format("%02d", (dateVal.get(Calendar.MONTH) + 1)))
                        .append(String.format("%02d", dateVal.get(Calendar.DAY_OF_MONTH))).toString());

        // Administrative gender code
        valueList.getValue()
                .add("PID-8|"
                        + ((patient.getGender().compareToIgnoreCase("female") == 0)
                                || (patient.getGender().compareToIgnoreCase("f") == 0)
                                        ? "F"
                                        : (((patient.getGender().compareToIgnoreCase("male") == 0)
                                                || (patient.getGender().compareToIgnoreCase("m") == 0) ? "M"
                                                        : "U"))));

        // Address info
        if ((patient.getAddress() != null) && (!patient.getAddress().isEmpty())) {
            StringBuilder address = new StringBuilder();
            address.append("PID-11|");

            // Street address line
            StringBuilder addressLine = new StringBuilder();
            for (StringDt lineItem : patient.getAddress().get(0).getLine()) {
                addressLine.append(lineItem.getValue());
            }
            address.append(addressLine + "^^");

            // City
            address.append(
                    ((patient.getAddress().get(0).getCity() != null) ? patient.getAddress().get(0).getCity()
                            : "") + "^");

            // State
            address.append(
                    ((patient.getAddress().get(0).getState() != null) ? patient.getAddress().get(0).getState()
                            : "") + "^");

            // Postal code
            address.append(((patient.getAddress().get(0).getPostalCode() != null)
                    ? patient.getAddress().get(0).getPostalCode()
                    : "") + "^");

            // Country
            address.append(((patient.getAddress().get(0).getCountry() != null)
                    ? patient.getAddress().get(0).getCountry()
                    : ""));

            valueList.getValue().add(address.toString());
        }

        slot.setValueList(valueList);
        extrinsicObject.getSlot().add(slot);

        // Create classifications - start with document author(s) represented in the Contract as the patient...
        ArrayList<ClassificationType> documentAuthorClassifications = new ArrayList<ClassificationType>();
        StringBuilder authorName = new StringBuilder();
        ClassificationType documentAuthorClassification = new ClassificationType();
        documentAuthorClassification.setId(UUID.randomUUID().toString());
        documentAuthorClassification.setClassificationScheme(documentAuthorClassificationScheme);
        documentAuthorClassification.setClassifiedObject("urn:uuid:" + newDocumentUuid.toString());
        documentAuthorClassification.setNodeRepresentation("");
        slot = new SlotType1();
        slot.setName("authorPerson");

        // authorPerson rim:Slot
        // Prefix
        authorName.append(((patient.getName().get(0).getPrefixAsSingleString() != null)
                ? (patient.getName().get(0).getPrefixAsSingleString() + " ")
                : ""));

        // Given name
        authorName.append(((patient.getName().get(0).getGivenAsSingleString() != null)
                ? (patient.getName().get(0).getGivenAsSingleString() + " ")
                : ""));

        // Family name
        authorName.append(((patient.getName().get(0).getFamilyAsSingleString() != null)
                ? (patient.getName().get(0).getFamilyAsSingleString())
                : ""));

        // Suffix
        authorName.append(((patient.getName().get(0).getSuffixAsSingleString() != null)
                ? (" " + patient.getName().get(0).getSuffixAsSingleString())
                : ""));

        valueList = new ValueListType();
        valueList.getValue().add(authorName.toString());
        slot.setValueList(valueList);
        documentAuthorClassification.getSlot().add(slot);

        documentAuthorClassifications.add(documentAuthorClassification);
        extrinsicObject.getClassification().add(documentAuthorClassification);

        // ClassCodes classification...
        ClassificationType classification = new ClassificationType();
        classification.setId(UUID.randomUUID().toString());
        classification.setClassificationScheme(documentClassCodesClassificationScheme);
        classification.setClassifiedObject("urn:uuid:" + newDocumentUuid.toString());

        classification.setNodeRepresentation(documentClassCodesNodeRepresentationContract);

        slot = new SlotType1();
        slot.setName("codingScheme");

        // Code system
        valueList = new ValueListType();
        valueList.getValue().add("1.3.6.1.4.1.21367.100.1");
        slot.setValueList(valueList);
        classification.getSlot().add(slot);

        // Display name
        InternationalStringType text = new InternationalStringType();
        LocalizedStringType localizedText = new LocalizedStringType();
        localizedText.setValue("Privacy Policy Acknowledgement Document");
        text.getLocalizedString().add(localizedText);
        classification.setName(text);

        extrinsicObject.getClassification().add(classification);

        // ConfidentialityCodes classification...
        classification = new ClassificationType();
        classification.setId(UUID.randomUUID().toString());
        classification.setClassificationScheme(documentConfidentialityCodesClassificationScheme);
        classification.setClassifiedObject("urn:uuid:" + newDocumentUuid.toString());
        // Code
        classification.setNodeRepresentation("N");

        slot = new SlotType1();
        slot.setName("codingScheme");

        // Code system
        valueList = new ValueListType();
        valueList.getValue().add("2.16.840.1.113883.5.25");
        slot.setValueList(valueList);
        classification.getSlot().add(slot);

        // Display name
        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue("Confidentiality Code");
        text.getLocalizedString().add(localizedText);
        classification.setName(text);

        extrinsicObject.getClassification().add(classification);

        // FormatCodes classification...
        classification = new ClassificationType();
        classification.setId(UUID.randomUUID().toString());
        classification.setClassificationScheme(documentFormatCodesClassificationScheme);
        classification.setClassifiedObject("urn:uuid:" + newDocumentUuid.toString());
        classification.setNodeRepresentation(documentFormatCodesNodeRepresentation);
        slot = new SlotType1();
        slot.setName("codingScheme");
        valueList = new ValueListType();
        valueList.getValue().add(documentFormatCodesCodingScheme);
        slot.setValueList(valueList);
        classification.getSlot().add(slot);
        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue(documentFormatCodesName);
        text.getLocalizedString().add(localizedText);
        classification.setName(text);
        extrinsicObject.getClassification().add(classification);

        // HealthcareFacilityTypeCodes classification...
        classification = new ClassificationType();
        classification.setId(UUID.randomUUID().toString());
        classification.setClassificationScheme(documentHealthcareFacilityTypeCodesClassificationScheme);
        classification.setClassifiedObject("urn:uuid:" + newDocumentUuid.toString());
        classification.setNodeRepresentation(documentHealthcareFacilityTypeCodesNodeRepresentation);
        slot = new SlotType1();
        slot.setName("codingScheme");
        valueList = new ValueListType();
        valueList.getValue().add(documentHealthcareFacilityTypeCodesCodingScheme);
        slot.setValueList(valueList);
        classification.getSlot().add(slot);
        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue(documentHealthcareFacilityTypeCodesName);
        text.getLocalizedString().add(localizedText);
        classification.setName(text);
        extrinsicObject.getClassification().add(classification);

        // PracticeSettingCodes classification...
        classification = new ClassificationType();
        classification.setId(UUID.randomUUID().toString());
        classification.setClassificationScheme(documentPracticeSettingCodesClassificationScheme);
        classification.setClassifiedObject("urn:uuid:" + newDocumentUuid.toString());
        classification.setNodeRepresentation(documentPracticeSettingCodesNodeRepresentation);

        slot = new SlotType1();
        slot.setName("codingScheme");

        valueList = new ValueListType();
        valueList.getValue().add(documentPracticeSettingCodesCodingScheme);
        slot.setValueList(valueList);
        classification.getSlot().add(slot);

        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue(documentPracticeSettingCodesDisplayName);
        text.getLocalizedString().add(localizedText);
        classification.setName(text);

        extrinsicObject.getClassification().add(classification);

        // Type code classification...
        classification = new ClassificationType();
        classification.setId(UUID.randomUUID().toString());
        classification.setClassificationScheme(documentContentTypeClassificationScheme);
        classification.setClassifiedObject("urn:uuid:" + newDocumentUuid.toString());

        // Code
        classification.setNodeRepresentation("57016-8");

        slot = new SlotType1();
        slot.setName("codingScheme");

        //  Code system
        valueList = new ValueListType();
        valueList.getValue().add("2.16.840.1.113883.6.1");
        slot.setValueList(valueList);
        classification.getSlot().add(slot);

        // Display name
        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue("Privacy Policy Acknowledgement Document");
        text.getLocalizedString().add(localizedText);
        classification.setName(text);

        extrinsicObject.getClassification().add(classification);

        // Create rim:ExternalIdentifier(s) - first the XDSDocumentEntry.patientId value(s)...
        ExternalIdentifierType externalIdentifierPatientId = new ExternalIdentifierType();
        externalIdentifierPatientId.setId(UUID.randomUUID().toString());
        externalIdentifierPatientId.setRegistryObject("urn:uuid:" + newDocumentUuid.toString());
        externalIdentifierPatientId
                .setIdentificationScheme(extrinsicObjectExternalIdentifierPatientIdIdentificationScheme);
        externalIdentifierPatientId.setValue(referencedId + "^^^&" + iExHubDomainOid + "&ISO");
        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue(extrinsicObjectExternalIdentifierPatientIdName);
        text.getLocalizedString().add(localizedText);
        externalIdentifierPatientId.setName(text);
        extrinsicObject.getExternalIdentifier().add(externalIdentifierPatientId);

        // Now the XDSDocumentEntry.uniqueId value(s)...
        ExternalIdentifierType externalIdentifierUniqueId = new ExternalIdentifierType();
        externalIdentifierUniqueId.setId(UUID.randomUUID().toString());
        externalIdentifierUniqueId.setRegistryObject("urn:uuid:" + newDocumentUuid.toString());
        externalIdentifierUniqueId
                .setIdentificationScheme(extrinsicObjectExternalIdentifierUniqueIdIdentificationScheme);

        //         if (testMode)
        //         {
        //            DateTime testDocId = DateTime.now(DateTimeZone.UTC);
        //            externalIdentifierDocumentId.setValue(contract.getIdentifier().getSystem()
        //                  + "^"
        //                  + testDocId.getMillis());
        //         }
        //         else
        //         {
        externalIdentifierUniqueId.setValue(//contract.getIdentifier().getSystem()
                //                  + "^"
                /*+*/ documentIdToUse);
        //         }

        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue(extrinsicObjectExternalIdentifierUniqueIdName);
        text.getLocalizedString().add(localizedText);
        externalIdentifierUniqueId.setName(text);
        extrinsicObject.getExternalIdentifier().add(externalIdentifierUniqueId);

        registryObjectList.getIdentifiable().add(objectFactory.createExtrinsicObject(extrinsicObject));

        // Create rim:RegistryPackage...
        String submissionSetId = UUID.randomUUID().toString();
        RegistryPackageType registryPackage = new RegistryPackageType();
        registryPackage.setId(submissionSetId);

        // Create rim:RegistryPackage/submissionTime attribute...
        slot = new SlotType1();
        slot.setName("submissionTime");
        valueList = new ValueListType();
        DateTime now = new DateTime(DateTimeZone.UTC);
        StringBuilder timeBuilder = new StringBuilder();
        timeBuilder.append(now.getYear());
        timeBuilder.append((now.getMonthOfYear() < 10) ? ("0" + now.getMonthOfYear()) : now.getMonthOfYear());
        timeBuilder.append((now.getDayOfMonth() < 10) ? ("0" + now.getDayOfMonth()) : now.getDayOfMonth());
        timeBuilder.append((now.getHourOfDay() < 10) ? ("0" + now.getHourOfDay()) : now.getHourOfDay());
        timeBuilder
                .append((now.getMinuteOfHour() < 10) ? ("0" + now.getMinuteOfHour()) : now.getMinuteOfHour());

        valueList.getValue().add(timeBuilder.toString());
        slot.setValueList(valueList);
        registryPackage.getSlot().add(slot);

        // Recreate authorName classification(s) in rim:RegistryPackage...
        for (ClassificationType registryClassification : documentAuthorClassifications) {
            ClassificationType newClassification = new ClassificationType();
            newClassification.setId(UUID.randomUUID().toString());
            newClassification.setClassificationScheme(registryPackageAuthorClassificationScheme);
            newClassification.setClassifiedObject(submissionSetId);
            newClassification.setNodeRepresentation("");

            if (!registryClassification.getSlot().isEmpty()) {
                slot = new SlotType1();
                slot.setName(registryClassification.getSlot().get(0).getName());
                slot.setValueList(registryClassification.getSlot().get(0).getValueList());
                newClassification.getSlot().add(slot);
            }

            registryPackage.getClassification().add(newClassification);
        }

        // ContentTypeCodes classification...
        classification = new ClassificationType();
        classification.setId(UUID.randomUUID().toString());
        classification.setClassificationScheme(registryPackageContentTypeCodesClassificationScheme);
        classification.setClassifiedObject(submissionSetId);
        // Code
        classification.setNodeRepresentation("57016-8");

        slot = new SlotType1();
        slot.setName("codingScheme");

        // Code system
        valueList = new ValueListType();
        valueList.getValue().add("2.16.840.1.113883.6.1");
        slot.setValueList(valueList);
        classification.getSlot().add(slot);

        // Display name
        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue("Privacy Policy Acknowledgement Document");
        text.getLocalizedString().add(localizedText);
        classification.setName(text);

        registryPackage.getClassification().add(classification);

        // ExternalIdentifiers - first XDSSubmissionSet.uniqueId...
        ExternalIdentifierType submissionSetUniqueId = new ExternalIdentifierType();
        submissionSetUniqueId.setId(UUID.randomUUID().toString());
        submissionSetUniqueId.setRegistryObject(submissionSetId);
        submissionSetUniqueId.setIdentificationScheme(registryPackageSubmissionSetUniqueIdIdentificationScheme);
        DateTime oidTimeValue = DateTime.now(DateTimeZone.UTC);
        submissionSetUniqueId.setValue(submissionSetOid + "." + oidTimeValue.getMillis());

        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue(externalIdentifierSubmissionSetUniqueIdName);
        text.getLocalizedString().add(localizedText);
        submissionSetUniqueId.setName(text);

        registryPackage.getExternalIdentifier().add(submissionSetUniqueId);

        // Now XDSSubmissionSet.sourceId...
        ExternalIdentifierType submissionSetSourceId = new ExternalIdentifierType();
        submissionSetSourceId.setId(UUID.randomUUID().toString());
        submissionSetSourceId.setRegistryObject(submissionSetId);
        submissionSetSourceId.setIdentificationScheme(registryPackageSubmissionSetSourceIdIdentificationScheme);
        submissionSetSourceId.setValue(iExHubDomainOid);

        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue(externalIdentifierSubmissionSetSourceIdName);
        text.getLocalizedString().add(localizedText);
        submissionSetSourceId.setName(text);

        registryPackage.getExternalIdentifier().add(submissionSetSourceId);

        // Now XDSSubmissionSet.patientId...
        ExternalIdentifierType submissionSetPatientId = new ExternalIdentifierType();
        submissionSetPatientId.setId(UUID.randomUUID().toString());
        submissionSetPatientId.setRegistryObject(submissionSetId);
        submissionSetPatientId
                .setIdentificationScheme(registryPackageSubmissionSetPatientIdIdentificationScheme);
        submissionSetPatientId.setValue(patientId);

        text = new InternationalStringType();
        localizedText = new LocalizedStringType();
        localizedText.setValue(externalIdentifierSubmissionSetPatientIdName);
        text.getLocalizedString().add(localizedText);
        submissionSetPatientId.setName(text);

        registryPackage.getExternalIdentifier().add(submissionSetPatientId);
        registryObjectList.getIdentifiable().add(objectFactory.createRegistryPackage(registryPackage));

        // Create SubmissionSet classification for RegistryObjectList...
        ClassificationType submissionSetClassification = new ClassificationType();
        submissionSetClassification.setId(UUID.randomUUID().toString());
        submissionSetClassification.setClassifiedObject(submissionSetId);
        submissionSetClassification.setClassificationNode(registryObjectListSubmissionSetClassificationNode);
        registryObjectList.getIdentifiable()
                .add(objectFactory.createClassification(submissionSetClassification));

        // Create SubmissionSet Association for RegistryObjectList...
        AssociationType1 submissionSetAssociation = new AssociationType1();
        submissionSetAssociation.setId(/*UUID.randomUUID().toString()*/ "as01");
        submissionSetAssociation
                .setAssociationType("urn:oasis:names:tc:ebxml-regrep:AssociationType:HasMember");
        submissionSetAssociation.setSourceObject(submissionSetId);
        submissionSetAssociation.setTargetObject("urn:uuid:" + newDocumentUuid.toString());

        slot = new SlotType1();
        slot.setName("SubmissionSetStatus");
        valueList = new ValueListType();
        valueList.getValue().add("Original");
        slot.setValueList(valueList);
        submissionSetAssociation.getSlot().add(slot);
        registryObjectList.getIdentifiable().add(objectFactory.createAssociation(submissionSetAssociation));

        // If updating a document, then we need to add another association which links the current document in the repository to this one...
        if (updateDocument) {
            AssociationType1 rplcAssociation = new AssociationType1();
            rplcAssociation.setId("Assoc1");
            rplcAssociation.setAssociationType("urn:ihe:iti:2007:AssociationType:RPLC");
            rplcAssociation.setTargetObject("urn:uuid:" + previousDocumentUuid.toString());
            rplcAssociation.setSourceObject("urn:uuid:" + newDocumentUuid.toString() ///*(contract.getIdentifier().getValue().startsWith("urn:uuid:")) ?*/ contract.getIdentifier().getValue()
            /*: "urn:uuid:" + contract.getIdentifier().getValue()*/);

            registryObjectList.getIdentifiable().add(objectFactory.createAssociation(rplcAssociation));

            // Replace old contract identifier with new one...
            contract.getId().setValueAsString(newDocumentUuid.toString());
        } else {
            contract.getId().setValueAsString(newDocumentUuid.toString());
        }

        submitObjectsRequest.setRegistryObjectList(registryObjectList);
        documentSetRequest.setSubmitObjectsRequest(submitObjectsRequest);

        // Add document to message...
        XdsBDocumentRepository.ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document documentForMessage = new XdsBDocumentRepository.ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document();
        documentForMessage.setValue(xmlContent);
        documentForMessage.setId("urn:uuid:" + newDocumentUuid.toString());
        documentSetRequest.getDocument().add(documentForMessage);

        logIti41AuditMsg(submissionSetId, patientId);

        if (logXdsBRequestMessages) {
            OMElement requestElement = repositoryStub.toOM(documentSetRequest,
                    repositoryStub.optimizeContent(new javax.xml.namespace.QName("urn:ihe:iti:xds-b:2007",
                            "ProvideAndRegisterDocumentSetRequest")),
                    new javax.xml.namespace.QName("urn:ihe:iti:xds-b:2007",
                            "ProvideAndRegisterDocumentSetRequest"));
            Files.write(
                    Paths.get(logOutputPath + newDocumentUuid.toString()
                            + "_ProvideAndRegisterDocumentSetRequest.xml"),
                    requestElement.toString().getBytes());
        }

        return repositoryStub.documentRepository_ProvideAndRegisterDocumentSetB(documentSetRequest);
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.integratedmodelling.time.literals.DurationValue.java

License:Open Source License

/**
 * Localize a duration to an extent starting at the current moment
 * using the same resolution that was implied in the generating 
 * text. For example, if the duration was one year, localize to the 
 * current year (jan 1st to dec 31st). Return the start and end points
 * of the extent./*  w w w.  j ava2  s  .co  m*/
 * 
 * @return
 */
public Pair<TimeValue, TimeValue> localize() {

    DateTime date = new DateTime();
    TimeValue start = null, end = null;
    long val = value;

    switch (precision) {

    case TemporalPrecision.MILLISECOND:
        start = new TimeValue(date);
        end = new TimeValue(date.plus(val));
        break;
    case TemporalPrecision.SECOND:
        val = value / DateTimeConstants.MILLIS_PER_SECOND;
        start = new TimeValue(new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                date.getHourOfDay(), date.getMinuteOfHour(), date.getSecondOfMinute(), 0));
        end = new TimeValue(start.getTimeData().plusSeconds((int) val));
        break;
    case TemporalPrecision.MINUTE:
        val = value / DateTimeConstants.MILLIS_PER_MINUTE;
        start = new TimeValue(new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                date.getHourOfDay(), date.getMinuteOfHour(), 0, 0));
        end = new TimeValue(start.getTimeData().plusMinutes((int) val));
        break;
    case TemporalPrecision.HOUR:
        val = value / DateTimeConstants.MILLIS_PER_HOUR;
        start = new TimeValue(new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                date.getHourOfDay(), 0, 0, 0));
        end = new TimeValue(start.getTimeData().plusHours((int) val));
        break;
    case TemporalPrecision.DAY:
        val = value / DateTimeConstants.MILLIS_PER_DAY;
        start = new TimeValue(
                new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), 0, 0, 0, 0));
        end = new TimeValue(start.getTimeData().plusDays((int) val));
        break;
    case TemporalPrecision.MONTH:
        start = new TimeValue(new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0, 0, 0));
        end = new TimeValue(start.getTimeData().plusMonths(origQuantity));
        break;
    case TemporalPrecision.YEAR:
        start = new TimeValue(new DateTime(date.getYear(), 1, 1, 0, 0, 0, 0));
        end = new TimeValue(start.getTimeData().plusYears(origQuantity));
        break;
    }

    return new Pair<TimeValue, TimeValue>(start, end);
}

From source file:org.isisaddons.app.kitchensink.fixture.date.DateObjectsFixture.java

License:Apache License

private DateObject create(final String name, final DateTime dt, final ExecutionContext ec) {
    final DateObject dateObject = dateObjects.createDateObject(name, dt.getYear(), dt.getMonthOfYear(),
            dt.getDayOfMonth(), dt.getHourOfDay(), dt.getMinuteOfHour());

    objects.add(dateObject);//from   w  w  w  .j av a2s  .c o  m

    return ec.addResult(this, dateObject);
}

From source file:org.itechkenya.leavemanager.api.DateTimeUtil.java

License:Open Source License

/**
 * @return true if dateTime1 and dateTime2 share the same day of month and month of year.
 *//*from   w  ww.  j a  v  a 2 s .  c o m*/
private static boolean shareDayAndMonth(DateTime dateTime1, DateTime dateTime2) {
    return dateTime1.getDayOfMonth() == dateTime2.getDayOfMonth()
            && dateTime1.getMonthOfYear() == dateTime2.getMonthOfYear();
}

From source file:org.itechkenya.leavemanager.domain.Contract.java

License:Open Source License

public BigDecimal calculateLeaveBalanceAtYearEnd(int year) {
    BigDecimal balance = BigDecimal.ZERO;
    if (this.calculateContractYear() > 1) {
        this.calculateLeaveEventValues();
        DateTime contractStartDateTime;
        for (LeaveEvent leaveEvent : this.getLeaveEventList()) {
            contractStartDateTime = new DateTime(this.getStartDate());
            Date contractDateThisYear = DateTimeUtil.createDate(year + 1,
                    contractStartDateTime.getMonthOfYear(), contractStartDateTime.getDayOfMonth());
            if (leaveEvent.getStartDate().compareTo(contractDateThisYear) != 1) {
                balance = leaveEvent.getBalance();
            }// w ww  .  j  a v a 2 s  .c  o  m
        }
    }
    return balance;
}

From source file:org.itechkenya.leavemanager.domain.Contract.java

License:Open Source License

public List<PreviouslyCompletedPeriod> calculatePreviouslyCompletedPeriod() {

    List<PreviouslyCompletedPeriod> previousCompletedPeriods = new ArrayList<>();

    DateTime today = new DateTime(new Date());
    DateTime contractStartDate = new DateTime(this.getStartDate());

    SimpleDateFormat monthSdf = new SimpleDateFormat("yyyyMM");
    SimpleDateFormat yearSdf = new SimpleDateFormat("yyyy");

    DateTime earnDateTime;/*w ww  . ja  va 2s  .c o m*/
    DateTime recordDateTime;
    Date date;

    if (today.getDayOfMonth() >= contractStartDate.getDayOfMonth()) {
        earnDateTime = today.minusMonths(1);
    } else {
        earnDateTime = today.minusMonths(2);
    }
    recordDateTime = earnDateTime.plusMonths(1);
    date = DateTimeUtil.createDate(recordDateTime.getYear(), recordDateTime.getMonthOfYear(),
            contractStartDate.getDayOfMonth());
    previousCompletedPeriods
            .add(new PreviouslyCompletedPeriod(monthSdf.format(earnDateTime.toDate()), date, PeriodType.MONTH));

    int contractYearCount = this.calculateContractYear();
    if (contractYearCount > 1) {
        int previousContractYear = this.calculatePreviousContractYear(contractYearCount);

        Date recordDate = DateTimeUtil.createDate(previousContractYear + 1, contractStartDate.getMonthOfYear(),
                contractStartDate.getDayOfMonth());

        previousCompletedPeriods.add(new PreviouslyCompletedPeriod(String.valueOf(previousContractYear),
                recordDate, PeriodType.YEAR));
    }
    return previousCompletedPeriods;
}

From source file:org.jarvis.core.services.CoreSunsetSunrise.java

License:Apache License

/**
 * write this object to statistics (base on next day)
 * @param lat /*from ww w. j  a v  a 2 s  .co m*/
 * @param lng 
 * @return String
 */
public SunApiRest get(String lat, String lng) {
    /**
     * build response
     */
    DateTime today = DateTime.now().plusDays(1);
    String d = today.getYear() + "-" + today.getMonthOfYear() + "-" + today.getDayOfMonth();
    Response entity;
    entity = client.target(baseurl).path("/json").queryParam("lat", lat).queryParam("lng", lng)
            .queryParam("date", d).queryParam("formatted", "0").request(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON).acceptEncoding("charset=UTF-8").get();

    /**
     * verify result
     */
    if (entity.getStatus() == 200) {
        String raw = entity.readEntity(String.class);
        SunApiResultRest result = null;
        try {
            result = mapper.readValue(raw, SunApiResultRest.class);
        } catch (IOException e) {
            throw new TechnicalException(e);
        }
        if (result == null) {
            return new SunApiRest();
        }
        return result.results;
    } else {
        throw new TechnicalException(entity.getStatus() + ":/json");
    }
}

From source file:org.jasig.portal.portlets.statistics.BaseStatisticsReportController.java

License:Apache License

/**
 * Build the aggregation {@link DataTable}
 *///from   ww  w  .  ja v a2  s .co m
protected final DataTable buildAggregationReport(F form) throws TypeMismatchException {
    //Pull data out of form for per-group fetching
    final AggregationInterval interval = form.getInterval();
    final DateMidnight start = form.getStart();
    final DateMidnight end = form.getEnd();

    final DateTime startDateTime = start.toDateTime();
    //Use a query end of the end date at 23:59:59
    final DateTime endDateTime = end.plusDays(1).toDateTime().minusSeconds(1);

    //Get the list of DateTimes used on the X axis in the report
    final List<DateTime> reportTimes = this.intervalHelper.getIntervalStartDateTimesBetween(interval,
            startDateTime, endDateTime, maxIntervals);

    final Map<D, SortedSet<T>> groupedAggregations = createColumnDiscriminatorMap(form);

    //Determine the ValueType of the date/time column. Use the most specific column type possible
    final ValueType dateTimeColumnType;
    if (interval.isHasTimePart()) {
        //If start/end are the same day just display the time
        if (startDateTime.toDateMidnight().equals(endDateTime.toDateMidnight())) {
            dateTimeColumnType = ValueType.TIMEOFDAY;
        }
        //interval has time data and start/end are on different days, show full date time
        else {
            dateTimeColumnType = ValueType.DATETIME;
        }
    }
    //interval is date only
    else {
        dateTimeColumnType = ValueType.DATE;
    }

    //Setup the date/time column description
    final ColumnDescription dateTimeColumn;
    switch (dateTimeColumnType) {
    case TIMEOFDAY: {
        dateTimeColumn = new ColumnDescription("time", dateTimeColumnType, "Time");
        break;
    }
    default: {
        dateTimeColumn = new ColumnDescription("date", dateTimeColumnType, "Date");
    }
    }

    final DataTable table = new JsonDataTable();
    table.addColumn(dateTimeColumn);

    //Setup columns in the DataTable 
    final Set<D> columnGroups = groupedAggregations.keySet();
    for (final D columnMapping : columnGroups) {
        final Collection<ColumnDescription> columnDescriptions = this.getColumnDescriptions(columnMapping,
                form);
        table.addColumns(columnDescriptions);
    }

    //Query for all aggregation data in the time range for all groups.  Only the
    //interval and discriminator data is used from the keys.
    final Set<K> keys = createAggregationsQueryKeyset(columnGroups, form);
    final BaseAggregationDao<T, K> baseAggregationDao = this.getBaseAggregationDao();
    final Collection<T> aggregations = baseAggregationDao.getAggregations(startDateTime, endDateTime, keys,
            extractGroupsArray(columnGroups));

    //Organize the results by group and sort them chronologically by adding them to the sorted set
    for (final T aggregation : aggregations) {
        final D discriminator = aggregation.getAggregationDiscriminator();
        final SortedSet<T> results = groupedAggregations.get(discriminator);
        results.add(aggregation);
    }

    //Build Map from discriminator column mapping to result iterator to allow putting results into
    //the correct column AND the correct time slot in the column
    Comparator<? super D> comparator = getDiscriminatorComparator();
    final Map<D, PeekingIterator<T>> groupedAggregationIterators = new TreeMap<D, PeekingIterator<T>>(
            (comparator));
    for (final Entry<D, SortedSet<T>> groupedAggregationEntry : groupedAggregations.entrySet()) {
        groupedAggregationIterators.put(groupedAggregationEntry.getKey(),
                Iterators.peekingIterator(groupedAggregationEntry.getValue().iterator()));
    }

    /*
     * populate the data, filling in blank spots. The full list of interval DateTimes is used to create every row in the
     * query range. Then the iterator
     */
    for (final DateTime rowTime : reportTimes) {
        // create the row
        final TableRow row = new TableRow();

        // add the date to the first cell
        final Value dateTimeValue;
        switch (dateTimeColumnType) {
        case DATE: {
            dateTimeValue = new DateValue(rowTime.getYear(), rowTime.getMonthOfYear() - 1,
                    rowTime.getDayOfMonth());
            break;
        }
        case TIMEOFDAY: {
            dateTimeValue = new TimeOfDayValue(rowTime.getHourOfDay(), rowTime.getMinuteOfHour(), 0);
            break;
        }
        default: {
            dateTimeValue = new DateTimeValue(rowTime.getYear(), rowTime.getMonthOfYear() - 1,
                    rowTime.getDayOfMonth(), rowTime.getHourOfDay(), rowTime.getMinuteOfHour(), 0, 0);
            break;
        }
        }
        row.addCell(new TableCell(dateTimeValue));

        for (final PeekingIterator<T> groupedAggregationIteratorEntry : groupedAggregationIterators.values()) {
            List<Value> values = null;

            if (groupedAggregationIteratorEntry.hasNext()) {
                final T aggr = groupedAggregationIteratorEntry.peek();
                if (rowTime.equals(aggr.getDateTime())) {
                    //Data is for the correct time slot, advance the iterator
                    groupedAggregationIteratorEntry.next();

                    values = createRowValues(aggr, form);
                }
            }

            //Gap in the data, fill it in using a null aggregation
            if (values == null) {
                values = createRowValues(null, form);
            }

            //Add the values to the row
            for (final Value value : values) {
                row.addCell(value);
            }
        }

        table.addRow(row);
    }

    return table;
}

From source file:org.jasig.portlet.calendar.adapter.ExchangeCalendarAdapter.java

License:Apache License

/**
 * Get an XMLGregorianCalendar for the specified date.
 *
 * @param date/*from ww  w  .  ja va 2 s .c o  m*/
 * @return
 * @throws DatatypeConfigurationException
 */
protected XMLGregorianCalendar getXmlDate(DateTime date) throws DatatypeConfigurationException {
    // construct an XMLGregorianCalendar
    DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    XMLGregorianCalendar start = datatypeFactory.newXMLGregorianCalendar();
    start.setYear(date.getYear());
    start.setMonth(date.getMonthOfYear());
    start.setTime(date.getHourOfDay(), date.getMinuteOfHour(), date.getSecondOfMinute(),
            date.getMillisOfSecond());
    start.setDay(date.getDayOfMonth());
    return start;
}

From source file:org.jbpm.designer.web.server.SimulationServlet.java

License:Apache License

private String getDateString(long seDate) {
    Date d = new Date(seDate);
    DateTime dt = new DateTime(seDate);
    StringBuffer retBuf = new StringBuffer();
    retBuf.append(dt.getYear()).append(",");
    retBuf.append(dt.getMonthOfYear()).append(",");
    retBuf.append(dt.getDayOfMonth()).append(",");
    retBuf.append(dt.getHourOfDay()).append(",");
    retBuf.append(dt.getMinuteOfHour()).append(",");
    retBuf.append(dt.getSecondOfMinute()).append(",");
    retBuf.append(dt.getMillisOfSecond());
    return retBuf.toString();
}