Example usage for org.joda.time DateTime getMinuteOfHour

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

Introduction

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

Prototype

public int getMinuteOfHour() 

Source Link

Document

Get the minute of hour field value.

Usage

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

License:Apache License

/**
 * @param fhirPatientResource//from  w w  w .  jav  a  2 s  .  c o  m
 * @return
 * @throws IOException
 */
public MCCIIN000002UV01 registerPatient(Patient fhirPatientResource) throws IOException {
    String dateOfBirth = (fhirPatientResource.getBirthDate() != null)
            ? fhirPatientResource.getBirthDateElement().getValueAsString()
            : null;
    String gender = (fhirPatientResource.getGender() == null) ? ""
            : (fhirPatientResource.getGender()
                    .compareToIgnoreCase(AdministrativeGenderEnum.MALE.getCode()) == 0)
                            ? "M"
                            : ((fhirPatientResource.getGender()
                                    .compareToIgnoreCase(AdministrativeGenderEnum.FEMALE.getCode()) == 0)
                                            ? "F"
                                            : ((fhirPatientResource.getGender().compareToIgnoreCase(
                                                    AdministrativeGenderEnum.OTHER.getCode()) == 0) ? "UN"
                                                            : ""));

    if ((fhirPatientResource.getName().get(0).getFamilyAsSingleString() == null)
            || (fhirPatientResource.getName().get(0).getFamilyAsSingleString().length() == 0)) {
        throw new FamilyNameParamMissingException("FamilyName parameter is required");
    }

    PRPAIN201301UV02 pRPA_IN201301UV02 = new PRPAIN201301UV02();

    // ITS version...
    pRPA_IN201301UV02.setITSVersion("XML_1.0");

    // ID...
    II messageId = new II();
    messageId.setRoot(iExHubDomainOid);
    messageId.setExtension(UUID.randomUUID().toString());
    pRPA_IN201301UV02.setId(messageId);

    // Creation time...
    DateTime dt = new DateTime(DateTimeZone.UTC);
    TS creationTime = new TS();
    StringBuilder creationTimeBuilder = new StringBuilder();
    creationTimeBuilder.append(dt.getYear());
    creationTimeBuilder.append((dt.getMonthOfYear() < 10) ? ("0" + dt.getMonthOfYear()) : dt.getMonthOfYear());
    creationTimeBuilder.append((dt.getDayOfMonth() < 10) ? ("0" + dt.getDayOfMonth()) : dt.getDayOfMonth());
    creationTimeBuilder.append((dt.getHourOfDay() < 10) ? ("0" + dt.getHourOfDay()) : dt.getHourOfDay());
    creationTimeBuilder
            .append((dt.getMinuteOfHour() < 10) ? ("0" + dt.getMinuteOfHour()) : dt.getMinuteOfHour());
    creationTimeBuilder
            .append((dt.getSecondOfMinute() < 10) ? ("0" + dt.getSecondOfMinute()) : dt.getSecondOfMinute());
    creationTime.setValue(creationTimeBuilder.toString());
    pRPA_IN201301UV02.setCreationTime(creationTime);

    // Interaction ID...
    II interactionId = new II();
    interactionId.setRoot("2.16.840.1.113883.1.6");
    interactionId.setExtension("PRPA_IN201301UV02");
    pRPA_IN201301UV02.setInteractionId(interactionId);

    // Processing code...
    CS processingCode = new CS();
    processingCode.setCode("P");
    pRPA_IN201301UV02.setProcessingCode(processingCode);

    // Processing mode code...
    CS processingModeCode = new CS();
    processingModeCode.setCode("T");
    pRPA_IN201301UV02.setProcessingModeCode(processingModeCode);

    // Accept ack code...
    CS acceptAckCode = new CS();
    acceptAckCode.setCode("AL");
    pRPA_IN201301UV02.setAcceptAckCode(acceptAckCode);

    // Create receiver...
    MCCIMT000100UV01Receiver receiver = new MCCIMT000100UV01Receiver();
    receiver.setTypeCode(CommunicationFunctionType.RCV);
    MCCIMT000100UV01Device receiverDevice = new MCCIMT000100UV01Device();
    receiverDevice.setClassCode(EntityClassDevice.DEV);
    receiverDevice.setDeterminerCode("INSTANCE");
    II receiverDeviceId = new II();
    receiverDeviceId.setRoot(receiverApplicationName);
    receiverDevice.getId().add(receiverDeviceId);
    MCCIMT000100UV01Agent asAgent = new MCCIMT000100UV01Agent();
    asAgent.getClassCode().add("AGNT");
    MCCIMT000100UV01Organization representedOrganization = new MCCIMT000100UV01Organization();
    representedOrganization.setDeterminerCode("INSTANCE");
    representedOrganization.setClassCode("ORG");
    II representedOrganizationId = new II();
    representedOrganizationId.setRoot(PIXManager.receiverApplicationRepresentedOrganization);
    representedOrganization.getId().add(representedOrganizationId);
    asAgent.setRepresentedOrganization(
            objectFactory.createMCCIMT000100UV01AgentRepresentedOrganization(representedOrganization));
    receiverDevice.setAsAgent(objectFactory.createMCCIMT000100UV01DeviceAsAgent(asAgent));
    receiver.setDevice(receiverDevice);
    pRPA_IN201301UV02.getReceiver().add(receiver);

    // Create sender...
    MCCIMT000100UV01Sender sender = new MCCIMT000100UV01Sender();
    sender.setTypeCode(CommunicationFunctionType.SND);
    MCCIMT000100UV01Device senderDevice = new MCCIMT000100UV01Device();
    senderDevice.setClassCode(EntityClassDevice.DEV);
    senderDevice.setDeterminerCode("INSTANCE");
    II senderDeviceId = new II();
    senderDeviceId.setRoot(PIXManager.iExHubSenderDeviceId);
    senderDevice.getId().add(senderDeviceId);
    MCCIMT000100UV01Agent senderAsAgent = new MCCIMT000100UV01Agent();
    senderAsAgent.getClassCode().add("AGNT");
    MCCIMT000100UV01Organization senderRepresentedOrganization = new MCCIMT000100UV01Organization();
    senderRepresentedOrganization.setDeterminerCode("INSTANCE");
    senderRepresentedOrganization.setClassCode("ORG");
    II senderRepresentedOrganizationId = new II();
    senderRepresentedOrganizationId.setRoot(PIXManager.iExHubDomainOid);
    senderRepresentedOrganization.getId().add(senderRepresentedOrganizationId);
    senderAsAgent.setRepresentedOrganization(
            objectFactory.createMCCIMT000100UV01AgentRepresentedOrganization(senderRepresentedOrganization));
    senderDevice.setAsAgent(objectFactory.createMCCIMT000100UV01DeviceAsAgent(senderAsAgent));
    sender.setDevice(senderDevice);
    pRPA_IN201301UV02.setSender(sender);

    PRPAIN201301UV02MFMIMT700701UV01Subject1 subject = new PRPAIN201301UV02MFMIMT700701UV01Subject1();

    // Create Registration Event...
    PRPAIN201301UV02MFMIMT700701UV01RegistrationEvent registrationEvent = new PRPAIN201301UV02MFMIMT700701UV01RegistrationEvent();
    registrationEvent.getClassCode().add("REG");
    registrationEvent.getMoodCode().add("EVN");
    registrationEvent.getNullFlavor().add("NA");
    CS statusCode = new CS();
    statusCode.setCode("active");
    registrationEvent.setStatusCode(statusCode);
    PRPAIN201301UV02MFMIMT700701UV01Subject2 subject1 = new PRPAIN201301UV02MFMIMT700701UV01Subject2();
    subject1.setTypeCode(ParticipationTargetSubject.SBJ);

    // Create Patient...
    PRPAMT201301UV02Patient patient = new PRPAMT201301UV02Patient();
    patient.getClassCode().add("PAT");
    CS patientStatusCode = new CS();
    patientStatusCode.setCode("active");
    patient.setStatusCode(patientStatusCode);

    // Create PatientPerson...
    PRPAMT201301UV02Person patientPerson = new PRPAMT201301UV02Person();

    // Other ID's specified...
    II constructedPatientId = null;
    if (fhirPatientResource.getIdentifier() != null) {
        for (IdentifierDt fhirId : fhirPatientResource.getIdentifier()) {
            if ((fhirId.getUse() != null) && (fhirId.getUse().equals(IdentifierUseEnum.OFFICIAL.getCode()))) {
                // This is the official identifier
                constructedPatientId = new II();
                if ((fhirId.getSystem() == null) || (fhirId.getSystem().length() == 0)) {
                    throw new PatientIdParamMissingException("Patient ID system missing");
                }
                constructedPatientId.setRoot((fhirId.getSystem().toLowerCase().startsWith(uriPrefix))
                        ? fhirId.getSystem().replace(uriPrefix, "")
                        : fhirId.getSystem());
                constructedPatientId.setExtension(fhirId.getValue());
                constructedPatientId.setAssigningAuthorityName(PIXManager.iExHubAssigningAuthority);
                patient.getId().add(constructedPatientId);
            } else {
                PRPAMT201301UV02OtherIDs asOtherId = new PRPAMT201301UV02OtherIDs();
                asOtherId.getClassCode().add("SD");
                II otherId = new II();
                otherId.setRoot(fhirId.getSystemElement().getValueAsString());
                otherId.setExtension(fhirId.getValue());
                asOtherId.getId().add(otherId);

                COCTMT150002UV01Organization scopingOrg = new COCTMT150002UV01Organization();
                scopingOrg.setClassCode("ORG");
                scopingOrg.setDeterminerCode("INSTANCE");
                II scopingOrgId = new II();
                scopingOrgId.setRoot(fhirId.getSystemElement().getValueAsString());
                scopingOrg.getId().add(scopingOrgId);
                asOtherId.setScopingOrganization(scopingOrg);

                patientPerson.getAsOtherIDs().add(asOtherId);
            }
        }
    }

    patientPerson.getName().add(populatePersonName(fhirPatientResource.getName().get(0)));

    if ((gender != null) && (gender.length() > 0)) {
        CE adminGenderCode = new CE();
        adminGenderCode.setCode(gender);
        adminGenderCode.setCodeSystem("2.16.840.1.113883.5.1");
        patientPerson.setAdministrativeGenderCode(adminGenderCode);
    } else {
        CE adminGenderCode = new CE();
        adminGenderCode.getNullFlavor().add("UNK");
        adminGenderCode.setCodeSystem("2.16.840.1.113883.5.1");
        patientPerson.setAdministrativeGenderCode(adminGenderCode);
    }

    patientPerson.getClassCode().add("PSN");
    patientPerson.setDeterminerCode("INSTANCE");

    if ((fhirPatientResource.getTelecom() != null) && (!fhirPatientResource.getTelecom().isEmpty())) {
        for (ContactPointDt contactPoint : fhirPatientResource.getTelecom()) {
            // Add if telecom value is present only
            if (contactPoint.getValue() != null && !contactPoint.getValue().isEmpty()) {
                TEL contactPartyTelecom = new TEL();
                contactPartyTelecom.setValue(contactPoint.getValue());
                patientPerson.getTelecom().add(contactPartyTelecom);
            }
        }
    }

    if (dateOfBirth != null) {
        // Try several formats for date parsing...
        DateTimeFormatter formatter = null;
        DateTime birthDateTime = null;
        try {
            formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
            birthDateTime = formatter.parseDateTime(dateOfBirth);
        } catch (Exception e) {
            try {
                formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
                birthDateTime = formatter.parseDateTime(dateOfBirth);
            } catch (Exception e2) {
                throw e2;
            }
        }

        StringBuilder birthDateBuilder = new StringBuilder();
        birthDateBuilder.append(birthDateTime.getYear());
        birthDateBuilder.append((birthDateTime.getMonthOfYear() < 10) ? ("0" + birthDateTime.getMonthOfYear())
                : birthDateTime.getMonthOfYear());
        birthDateBuilder.append((birthDateTime.getDayOfMonth() < 10) ? ("0" + birthDateTime.getDayOfMonth())
                : birthDateTime.getDayOfMonth());
        TS birthTime = new TS();
        birthTime.setValue(birthDateBuilder.toString());
        patientPerson.setBirthTime(birthTime);
    }

    JAXBElement<PRPAMT201301UV02Person> patientPersonElement = objectFactory
            .createPRPAMT201301UV02PatientPatientPerson(patientPerson);
    patient.setPatientPerson(patientPersonElement);

    // Create ProviderOrganization - set IExHub as provider if no careProvider specified in FHIR patient resource parameter...
    COCTMT150003UV03Organization providerOrganization = new COCTMT150003UV03Organization();
    providerOrganization.setDeterminerCode("INSTANCE");
    providerOrganization.setClassCode("ORG");

    if ((fhirPatientResource.getCareProvider() != null) && (!fhirPatientResource.getCareProvider().isEmpty())) {
        for (ResourceReferenceDt resourceRef : fhirPatientResource.getCareProvider()) {
            if (resourceRef.getResource().getClass() == Organization.class) {
                Organization careProvider = (Organization) resourceRef.getResource();

                // Provider ID
                II providerId = new II();
                providerId.setRoot((careProvider.getId().getValueAsString().startsWith("#"))
                        ? careProvider.getId().getValueAsString().substring(1)
                        : careProvider.getId().getValueAsString());
                providerOrganization.getId().add(providerId);

                // Provider name
                if ((careProvider.getName() != null) && (careProvider.getName().length() > 0)) {
                    ON providerName = new ON();
                    providerName.getContent().add(careProvider.getName());
                    providerOrganization.getName().add(providerName);
                }

                // Create Contact Party if FHIR organization contacts are present...
                for (Contact fhirOrganizationContact : careProvider.getContact()) {
                    COCTMT150003UV03ContactParty contactParty = new COCTMT150003UV03ContactParty();
                    contactParty.setClassCode(RoleClassContact.CON);

                    // Contact telecom(s)
                    if ((fhirOrganizationContact.getTelecom() != null)
                            && (!fhirOrganizationContact.getTelecom().isEmpty())) {
                        for (ContactPointDt contactPoint : fhirOrganizationContact.getTelecom()) {
                            TEL contactPartyTelecom = new TEL();
                            contactPartyTelecom.setValue(contactPoint.getValue());
                            contactParty.getTelecom().add(contactPartyTelecom);
                        }
                    }

                    // Contact name
                    if ((fhirOrganizationContact.getName() != null)
                            && (!fhirOrganizationContact.getName().isEmpty())) {
                        COCTMT150003UV03Person contactPerson = new COCTMT150003UV03Person();
                        contactPerson.getName().add(populatePersonName(fhirOrganizationContact.getName()));
                        contactParty.setContactPerson(
                                objectFactory.createCOCTMT150003UV03ContactPartyContactPerson(contactPerson));
                    }

                    // Contact address(es)
                    if ((careProvider.getAddress() != null) && (!careProvider.getAddress().isEmpty())) {
                        for (AddressDt fhirAddr : careProvider.getAddress()) {
                            contactParty.getAddr().add(populatePatientAddress(fhirAddr));
                        }
                    }

                    providerOrganization.getContactParty().add(contactParty);
                }
            }
        }
    } else {
        II providerId = new II();
        providerId.setRoot(providerOrganizationOid);
        providerOrganization.getId().add(providerId);
        ON providerName = new ON();
        providerName.getContent().add(providerOrganizationName);
        providerOrganization.getName().add(providerName);
        COCTMT150003UV03ContactParty contactParty = new COCTMT150003UV03ContactParty();
        contactParty.setClassCode(RoleClassContact.CON);
        TEL contactPartyTelecom = new TEL();
        contactPartyTelecom.setValue(providerOrganizationContactTelecom);
        contactParty.getTelecom().add(contactPartyTelecom);
        providerOrganization.getContactParty().add(contactParty);
    }

    patient.setProviderOrganization(providerOrganization);

    subject1.setPatient(patient);

    registrationEvent.setSubject1(subject1);

    // Create Custodian info...
    MFMIMT700701UV01Custodian custodian = new MFMIMT700701UV01Custodian();
    custodian.getTypeCode().add("CST");
    COCTMT090003UV01AssignedEntity assignedEntity = new COCTMT090003UV01AssignedEntity();
    assignedEntity.setClassCode("ASSIGNED");
    II assignedEntityId = new II();
    assignedEntityId.setRoot(iExHubDomainOid);
    assignedEntity.getId().add(assignedEntityId);
    COCTMT090003UV01Organization assignedOrganization = new COCTMT090003UV01Organization();
    assignedOrganization.setDeterminerCode("INSTANCE");
    assignedOrganization.setClassCode("ORG");
    EN organizationName = new EN();
    organizationName.getContent().add("IHE Portal");
    assignedOrganization.getName().add(organizationName);
    assignedEntity.setAssignedOrganization(
            objectFactory.createCOCTMT090003UV01AssignedEntityAssignedOrganization(assignedOrganization));
    custodian.setAssignedEntity(assignedEntity);
    registrationEvent.setCustodian(custodian);

    // Set Subject info...
    subject.getTypeCode().add("SUBJ");

    subject.setRegistrationEvent(registrationEvent);

    PRPAIN201301UV02MFMIMT700701UV01ControlActProcess controlAct = new PRPAIN201301UV02MFMIMT700701UV01ControlActProcess();
    CD controlActProcessCode = new CD();
    controlActProcessCode.setCode("PRPA_TE201301UV02");
    controlActProcessCode.setCodeSystem("2.16.840.1.113883.1.6");
    controlAct.setCode(controlActProcessCode);
    controlAct.setClassCode(ActClassControlAct.CACT);
    controlAct.setMoodCode(XActMoodIntentEvent.EVN);
    controlAct.getSubject().add(subject);

    pRPA_IN201301UV02.setControlActProcess(controlAct);

    logIti44AuditMsg(constructedPatientId.getExtension() + "^^^&" + constructedPatientId.getRoot() + "&"
            + PIXManager.iExHubAssigningAuthority);

    UUID logMsgId = null;
    if (logPixRequestMessages) {
        logMsgId = UUID.randomUUID();
        OMElement requestElement = pixManagerStub.toOM(pRPA_IN201301UV02,
                pixManagerStub
                        .optimizeContent(new javax.xml.namespace.QName("urn:hl7-org:v3", "PRPA_IN201301UV02")),
                new javax.xml.namespace.QName("urn:hl7-org:v3", "PRPA_IN201301UV02"));
        Files.write(Paths.get(logOutputPath + logMsgId.toString() + "_PIXRegisterPatientRequest.xml"),
                requestElement.toString().getBytes());
    }

    MCCIIN000002UV01 response = pixManagerStub.pIXManager_PRPA_IN201301UV02(pRPA_IN201301UV02);
    if (logPixResponseMessages) {
        OMElement responseElement = pixManagerStub.toOM(response,
                pixManagerStub
                        .optimizeContent(new javax.xml.namespace.QName("urn:hl7-org:v3", "MCCI_IN000002UV01")),
                new javax.xml.namespace.QName("urn:hl7-org:v3", "MCCI_IN000002UV01"));
        Files.write(Paths
                .get(logOutputPath + ((logMsgId == null) ? UUID.randomUUID().toString() : logMsgId.toString())
                        + "_PIXRegisterPatientResponse.xml"),
                responseElement.toString().getBytes());
    }

    return response;
}

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

License:Apache License

/**
 * @param givenName/*w  w w.j av  a2  s.  com*/
 * @param familyName
 * @param middleName
 * @param dateOfBirth
 * @param gender
 * @param patientId
 * @return
 * @throws IOException
 */
public MCCIIN000002UV01 registerPatient(String givenName, String familyName, String middleName,
        String dateOfBirth, String gender, String patientId) throws IOException {
    if ((familyName == null) || (familyName.length() == 0)) {
        throw new FamilyNameParamMissingException("FamilyName parameter is required");
    }

    PRPAIN201301UV02 pRPA_IN201301UV02 = new PRPAIN201301UV02();

    // ITS version...
    pRPA_IN201301UV02.setITSVersion("XML_1.0");

    // ID...
    II messageId = new II();
    messageId.setRoot(iExHubDomainOid);
    messageId.setExtension(UUID.randomUUID().toString());
    pRPA_IN201301UV02.setId(messageId);

    // Creation time...
    DateTime dt = new DateTime(DateTimeZone.UTC);
    TS creationTime = new TS();
    StringBuilder creationTimeBuilder = new StringBuilder();
    creationTimeBuilder.append(dt.getYear());
    creationTimeBuilder.append((dt.getMonthOfYear() < 10) ? ("0" + dt.getMonthOfYear()) : dt.getMonthOfYear());
    creationTimeBuilder.append((dt.getDayOfMonth() < 10) ? ("0" + dt.getDayOfMonth()) : dt.getDayOfMonth());
    creationTimeBuilder.append((dt.getHourOfDay() < 10) ? ("0" + dt.getHourOfDay()) : dt.getHourOfDay());
    creationTimeBuilder
            .append((dt.getMinuteOfHour() < 10) ? ("0" + dt.getMinuteOfHour()) : dt.getMinuteOfHour());
    creationTimeBuilder
            .append((dt.getSecondOfMinute() < 10) ? ("0" + dt.getSecondOfMinute()) : dt.getSecondOfMinute());
    creationTime.setValue(creationTimeBuilder.toString());
    pRPA_IN201301UV02.setCreationTime(creationTime);

    // Interaction ID...
    II interactionId = new II();
    interactionId.setRoot("2.16.840.1.113883.1.6");
    interactionId.setExtension("PRPA_IN201301UV02");
    pRPA_IN201301UV02.setInteractionId(interactionId);

    // Processing code...
    CS processingCode = new CS();
    processingCode.setCode("P");
    pRPA_IN201301UV02.setProcessingCode(processingCode);

    // Processing mode code...
    CS processingModeCode = new CS();
    processingModeCode.setCode("T");
    pRPA_IN201301UV02.setProcessingModeCode(processingModeCode);

    // Accept ack code...
    CS acceptAckCode = new CS();
    acceptAckCode.setCode("AL");
    pRPA_IN201301UV02.setAcceptAckCode(acceptAckCode);

    // Create receiver...
    MCCIMT000100UV01Receiver receiver = new MCCIMT000100UV01Receiver();
    receiver.setTypeCode(CommunicationFunctionType.RCV);
    MCCIMT000100UV01Device receiverDevice = new MCCIMT000100UV01Device();
    receiverDevice.setClassCode(EntityClassDevice.DEV);
    receiverDevice.setDeterminerCode("INSTANCE");
    II receiverDeviceId = new II();
    receiverDeviceId.setRoot(receiverApplicationName);
    receiverDevice.getId().add(receiverDeviceId);
    MCCIMT000100UV01Agent asAgent = new MCCIMT000100UV01Agent();
    asAgent.getClassCode().add("AGNT");
    MCCIMT000100UV01Organization representedOrganization = new MCCIMT000100UV01Organization();
    representedOrganization.setDeterminerCode("INSTANCE");
    representedOrganization.setClassCode("ORG");
    II representedOrganizationId = new II();
    representedOrganizationId.setRoot(PIXManager.receiverApplicationRepresentedOrganization);
    representedOrganization.getId().add(representedOrganizationId);
    asAgent.setRepresentedOrganization(
            objectFactory.createMCCIMT000100UV01AgentRepresentedOrganization(representedOrganization));
    receiverDevice.setAsAgent(objectFactory.createMCCIMT000100UV01DeviceAsAgent(asAgent));
    receiver.setDevice(receiverDevice);
    pRPA_IN201301UV02.getReceiver().add(receiver);

    // Create sender...
    MCCIMT000100UV01Sender sender = new MCCIMT000100UV01Sender();
    sender.setTypeCode(CommunicationFunctionType.SND);
    MCCIMT000100UV01Device senderDevice = new MCCIMT000100UV01Device();
    senderDevice.setClassCode(EntityClassDevice.DEV);
    senderDevice.setDeterminerCode("INSTANCE");
    II senderDeviceId = new II();
    senderDeviceId.setRoot(PIXManager.iExHubSenderDeviceId);
    senderDevice.getId().add(senderDeviceId);
    MCCIMT000100UV01Agent senderAsAgent = new MCCIMT000100UV01Agent();
    senderAsAgent.getClassCode().add("AGNT");
    MCCIMT000100UV01Organization senderRepresentedOrganization = new MCCIMT000100UV01Organization();
    senderRepresentedOrganization.setDeterminerCode("INSTANCE");
    senderRepresentedOrganization.setClassCode("ORG");
    II senderRepresentedOrganizationId = new II();
    senderRepresentedOrganizationId.setRoot(PIXManager.iExHubDomainOid);
    senderRepresentedOrganization.getId().add(senderRepresentedOrganizationId);
    senderAsAgent.setRepresentedOrganization(
            objectFactory.createMCCIMT000100UV01AgentRepresentedOrganization(senderRepresentedOrganization));
    senderDevice.setAsAgent(objectFactory.createMCCIMT000100UV01DeviceAsAgent(senderAsAgent));
    sender.setDevice(senderDevice);
    pRPA_IN201301UV02.setSender(sender);

    PRPAIN201301UV02MFMIMT700701UV01Subject1 subject = new PRPAIN201301UV02MFMIMT700701UV01Subject1();

    // Create Registration Event...
    PRPAIN201301UV02MFMIMT700701UV01RegistrationEvent registrationEvent = new PRPAIN201301UV02MFMIMT700701UV01RegistrationEvent();
    registrationEvent.getClassCode().add("REG");
    registrationEvent.getMoodCode().add("EVN");
    registrationEvent.getNullFlavor().add("NA");
    CS statusCode = new CS();
    statusCode.setCode("active");
    registrationEvent.setStatusCode(statusCode);
    PRPAIN201301UV02MFMIMT700701UV01Subject2 subject1 = new PRPAIN201301UV02MFMIMT700701UV01Subject2();
    subject1.setTypeCode(ParticipationTargetSubject.SBJ);

    // Create Patient...
    PRPAMT201301UV02Patient patient = new PRPAMT201301UV02Patient();
    patient.getClassCode().add("PAT");

    II constructedPatientId = new II();
    constructedPatientId.setRoot(PIXManager.patientIdAssigningAuthority);
    constructedPatientId.setExtension(UUID.randomUUID().toString());
    constructedPatientId.setAssigningAuthorityName(PIXManager.iExHubAssigningAuthority);
    patient.getId().add(constructedPatientId);

    CS patientStatusCode = new CS();
    patientStatusCode.setCode("active");
    patient.setStatusCode(patientStatusCode);

    // Create PatientPerson...
    PRPAMT201301UV02Person patientPerson = new PRPAMT201301UV02Person();

    //      // Other ID's specified...
    //      if (fhirIdentifiers != null)
    //      {
    //         for (IdentifierDt fhirId : fhirIdentifiers)
    //         {
    //            PRPAMT201301UV02OtherIDs asOtherId = new PRPAMT201301UV02OtherIDs();
    //            asOtherId.getClassCode().add("SD");
    //            II otherId = new II();
    //            otherId.setRoot(fhirId.getSystemElement().getValueAsString());
    //            otherId.setExtension(fhirId.getValue());
    //            asOtherId.getId().add(otherId);
    //            
    //            COCTMT150002UV01Organization scopingOrg = new COCTMT150002UV01Organization();
    //            scopingOrg.setClassCode("ORG");
    //            scopingOrg.setDeterminerCode("INSTANCE");
    //            II scopingOrgId = new II();
    //            scopingOrgId.setRoot(fhirId.getSystemElement().getValueAsString());
    //            scopingOrg.getId().add(scopingOrgId);
    //            asOtherId.setScopingOrganization(scopingOrg);
    //            
    //            patientPerson.getAsOtherIDs().add(asOtherId);
    //         }
    //      }

    EnFamily enFamily = null;
    if ((familyName != null) && (familyName.length() > 0)) {
        enFamily = new EnFamily();
        enFamily.getContent().add(familyName);
    }

    EnGiven enGiven = null;
    if ((givenName != null) && (givenName.length() > 0)) {
        enGiven = new EnGiven();

        if ((middleName != null) && (middleName.length() > 0)) {
            enGiven.getContent().add(givenName + " " + middleName);
        } else {
            enGiven.getContent().add(givenName);
        }
    }

    PN patientName = new PN();
    patientName.getContent().add(objectFactory.createENFamily(enFamily));

    if (enGiven != null) {
        patientName.getContent().add(objectFactory.createENGiven(enGiven));
    }

    patientPerson.getName().add(patientName);

    if ((gender != null) && (gender.length() > 0)) {
        CE adminGenderCode = new CE();
        adminGenderCode.setCode(gender);
        adminGenderCode.setCodeSystem("2.16.840.1.113883.5.1");
        patientPerson.setAdministrativeGenderCode(adminGenderCode);
    } else {
        CE adminGenderCode = new CE();
        adminGenderCode.getNullFlavor().add("UNK");
        adminGenderCode.setCodeSystem("2.16.840.1.113883.5.1");
        patientPerson.setAdministrativeGenderCode(adminGenderCode);
    }

    patientPerson.getClassCode().add("PSN");
    patientPerson.setDeterminerCode("INSTANCE");

    if (dateOfBirth != null) {
        // Try several formats for date parsing...
        DateTimeFormatter formatter = null;
        DateTime birthDateTime = null;
        try {
            formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
            birthDateTime = formatter.parseDateTime(dateOfBirth);
        } catch (Exception e) {
            try {
                formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
                birthDateTime = formatter.parseDateTime(dateOfBirth);
            } catch (Exception e2) {
                throw e2;
            }
        }

        StringBuilder birthDateBuilder = new StringBuilder();
        birthDateBuilder.append(birthDateTime.getYear());
        birthDateBuilder.append((birthDateTime.getMonthOfYear() < 10) ? ("0" + birthDateTime.getMonthOfYear())
                : birthDateTime.getMonthOfYear());
        birthDateBuilder.append((birthDateTime.getDayOfMonth() < 10) ? ("0" + birthDateTime.getDayOfMonth())
                : birthDateTime.getDayOfMonth());
        TS birthTime = new TS();
        birthTime.setValue(birthDateBuilder.toString());
        patientPerson.setBirthTime(birthTime);
    }

    JAXBElement<PRPAMT201301UV02Person> patientPersonElement = objectFactory
            .createPRPAMT201301UV02PatientPatientPerson(patientPerson);
    patient.setPatientPerson(patientPersonElement);

    // Create ProviderOrganization...
    COCTMT150003UV03Organization providerOrganization = new COCTMT150003UV03Organization();
    providerOrganization.setDeterminerCode("INSTANCE");
    providerOrganization.setClassCode("ORG");
    II providerId = new II();
    providerId.setRoot(providerOrganizationOid);
    providerOrganization.getId().add(providerId);
    ON providerName = new ON();
    providerName.getContent().add(providerOrganizationName);
    providerOrganization.getName().add(providerName);
    COCTMT150003UV03ContactParty contactParty = new COCTMT150003UV03ContactParty();
    contactParty.setClassCode(RoleClassContact.CON);
    TEL contactPartyTelecom = new TEL();
    contactPartyTelecom.setValue(providerOrganizationContactTelecom);
    contactParty.getTelecom().add(contactPartyTelecom);
    providerOrganization.getContactParty().add(contactParty);

    patient.setProviderOrganization(providerOrganization);

    subject1.setPatient(patient);

    registrationEvent.setSubject1(subject1);

    // Create Custodian info...
    MFMIMT700701UV01Custodian custodian = new MFMIMT700701UV01Custodian();
    custodian.getTypeCode().add("CST");
    COCTMT090003UV01AssignedEntity assignedEntity = new COCTMT090003UV01AssignedEntity();
    assignedEntity.setClassCode("ASSIGNED");
    II assignedEntityId = new II();
    assignedEntityId.setRoot(iExHubDomainOid);
    assignedEntity.getId().add(assignedEntityId);
    COCTMT090003UV01Organization assignedOrganization = new COCTMT090003UV01Organization();
    assignedOrganization.setDeterminerCode("INSTANCE");
    assignedOrganization.setClassCode("ORG");
    EN organizationName = new EN();
    organizationName.getContent().add("IHE Portal");
    assignedOrganization.getName().add(organizationName);
    assignedEntity.setAssignedOrganization(
            objectFactory.createCOCTMT090003UV01AssignedEntityAssignedOrganization(assignedOrganization));
    custodian.setAssignedEntity(assignedEntity);
    registrationEvent.setCustodian(custodian);

    // Set Subject info...
    subject.getTypeCode().add("SUBJ");

    subject.setRegistrationEvent(registrationEvent);

    PRPAIN201301UV02MFMIMT700701UV01ControlActProcess controlAct = new PRPAIN201301UV02MFMIMT700701UV01ControlActProcess();
    CD controlActProcessCode = new CD();
    controlActProcessCode.setCode("PRPA_TE201301UV02");
    controlActProcessCode.setCodeSystem("2.16.840.1.113883.1.6");
    controlAct.setCode(controlActProcessCode);
    controlAct.setClassCode(ActClassControlAct.CACT);
    controlAct.setMoodCode(XActMoodIntentEvent.EVN);
    controlAct.getSubject().add(subject);

    pRPA_IN201301UV02.setControlActProcess(controlAct);

    logIti44AuditMsg(
            patientId + "^^^&" + PIXManager.iExHubDomainOid + "&" + PIXManager.iExHubAssigningAuthority);

    UUID logMsgId = null;
    if (logPixRequestMessages) {
        logMsgId = UUID.randomUUID();
        OMElement requestElement = pixManagerStub.toOM(pRPA_IN201301UV02,
                pixManagerStub
                        .optimizeContent(new javax.xml.namespace.QName("urn:hl7-org:v3", "PRPA_IN201301UV02")),
                new javax.xml.namespace.QName("urn:hl7-org:v3", "PRPA_IN201301UV02"));
        Files.write(Paths.get(logOutputPath + logMsgId.toString() + "_PIXRegisterPatientRequest.xml"),
                requestElement.toString().getBytes());
    }

    MCCIIN000002UV01 response = pixManagerStub.pIXManager_PRPA_IN201301UV02(pRPA_IN201301UV02);
    if (logPixResponseMessages) {
        OMElement responseElement = pixManagerStub.toOM(response,
                pixManagerStub
                        .optimizeContent(new javax.xml.namespace.QName("urn:hl7-org:v3", "MCCI_IN000002UV01")),
                new javax.xml.namespace.QName("urn:hl7-org:v3", "MCCI_IN000002UV01"));
        Files.write(Paths
                .get(logOutputPath + ((logMsgId == null) ? UUID.randomUUID().toString() : logMsgId.toString())
                        + "_PIXRegisterPatientResponse.xml"),
                responseElement.toString().getBytes());
    }

    return response;
}

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

License:Apache License

/**
 * @param cdaDocument//from   www  .j a v a2  s.c  o m
 * @param mimeType
 * @return
 * @throws Exception
 */
public RegistryResponseType provideAndRegisterDocumentSet(byte[] cdaDocument, String mimeType)
        throws Exception {
    // Support only for a single document per submission set...
    if (mimeType.compareToIgnoreCase("text/xml") != 0) {
        throw new DocumentTypeUnsupportedException(
                "Only XML documents currently supported for ProvideAndRegisterDocumentSet");
    }

    try {
        ProvideAndRegisterDocumentSetRequestType documentSetRequest = new ProvideAndRegisterDocumentSetRequestType();

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

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

        // Create ExtrinsicObject...
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputStream is = new ByteArrayInputStream(cdaDocument);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        Document doc = dBuilder.parse(new InputSource(reader));

        String documentId = UUID.randomUUID().toString();
        ExtrinsicObjectType extrinsicObject = new ExtrinsicObjectType();
        extrinsicObject.setId(documentId);
        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");
        XPath xPath = getCustomXPath();
        NodeList nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:effectiveTime",
                doc.getDocumentElement(), XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            valueList = new ValueListType();
            valueList.getValue().add(((Element) nodes.item(0)).getAttribute("value"));
            slot.setValueList(valueList);
            extrinsicObject.getSlot().add(slot);
        }

        // Create languageCode rim:Slot...
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:languageCode", doc.getDocumentElement(),
                XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            slot = new SlotType1();
            slot.setName("languageCode");
            valueList = new ValueListType();
            valueList.getValue().add(((Element) nodes.item(0)).getAttribute("code"));
            slot.setValueList(valueList);
            extrinsicObject.getSlot().add(slot);
        }

        // Create serviceStartTime rim:Slot...
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate(
                "/hl7:ClinicalDocument/hl7:documentationOf/hl7:serviceEvent/hl7:effectiveTime/hl7:low",
                doc.getDocumentElement(), XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            slot = new SlotType1();
            slot.setName("serviceStartTime");
            valueList = new ValueListType();
            valueList.getValue().add(((Element) nodes.item(0)).getAttribute("value"));
            slot.setValueList(valueList);
            extrinsicObject.getSlot().add(slot);
        }

        // Create serviceStopTime rim:Slot...
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate(
                "/hl7:ClinicalDocument/hl7:documentationOf/hl7:serviceEvent/hl7:effectiveTime/high",
                doc.getDocumentElement(), XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            slot = new SlotType1();
            slot.setName("serviceStopTime");
            valueList = new ValueListType();
            valueList.getValue().add(((Element) nodes.item(0)).getAttribute("value"));
            slot.setValueList(valueList);
            extrinsicObject.getSlot().add(slot);
        }

        // Create sourcePatientId rim:Slot...
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:id",
                doc.getDocumentElement(), XPathConstants.NODESET);
        String patientId = null;
        if (nodes.getLength() > 0) {
            slot = new SlotType1();
            slot.setName("sourcePatientId");
            valueList = new ValueListType();
            patientId = ((Element) nodes.item(0)).getAttribute("extension") + "^^^&"
                    + ((Element) nodes.item(0)).getAttribute("root") + "&ISO";
            valueList.getValue().add(patientId);
            slot.setValueList(valueList);
            extrinsicObject.getSlot().add(slot);
        }

        // Create sourcePatientInfo rim:Slot...
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate(
                "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:patient/hl7:name/hl7:family",
                doc.getDocumentElement(), XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            slot = new SlotType1();
            slot.setName("sourcePatientInfo");
            valueList = new ValueListType();
            valueList.getValue().add("PID-3|" + patientId);

            StringBuilder name = new StringBuilder();
            name.append("PID-5|" + ((Element) nodes.item(0)).getTextContent() + "^");

            xPath = getCustomXPath();
            nodes = (NodeList) xPath.evaluate(
                    "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:patient/hl7:name/hl7:given",
                    doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                name.append(((Element) nodes.item(0)).getTextContent() + "^^");
            } else {
                name.append("^^");
            }

            xPath = getCustomXPath();
            nodes = (NodeList) xPath.evaluate(
                    "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:patient/hl7:name/hl7:prefix",
                    doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                name.append(((Element) nodes.item(0)).getTextContent() + "^");
            } else {
                name.append("^");
            }

            xPath = getCustomXPath();
            nodes = (NodeList) xPath.evaluate(
                    "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:patient/hl7:name/hl7:suffix",
                    doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                name.append(((Element) nodes.item(0)).getTextContent());
            }

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

            xPath = getCustomXPath();
            nodes = (NodeList) xPath.evaluate(
                    "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:patient/hl7:birthTime",
                    doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                valueList.getValue().add("PID-7|" + ((Element) nodes.item(0)).getAttribute("value"));
            }

            xPath = getCustomXPath();
            nodes = (NodeList) xPath.evaluate(
                    "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:patient/hl7:administrativeGenderCode",
                    doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                valueList.getValue().add("PID-8|" + ((Element) nodes.item(0)).getAttribute("code"));
            }

            xPath = getCustomXPath();
            nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:addr",
                    doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                StringBuilder address = new StringBuilder();
                address.append("PID-11|");

                xPath = getCustomXPath();
                nodes = (NodeList) xPath.evaluate(
                        "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:addr/hl7:streetAddressLine",
                        doc.getDocumentElement(), XPathConstants.NODESET);
                if (nodes.getLength() > 0) {
                    address.append(((Element) nodes.item(0)).getTextContent() + "^^");
                } else {
                    address.append("^^");
                }

                xPath = getCustomXPath();
                nodes = (NodeList) xPath.evaluate(
                        "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:addr/hl7:city",
                        doc.getDocumentElement(), XPathConstants.NODESET);
                if (nodes.getLength() > 0) {
                    address.append(((Element) nodes.item(0)).getTextContent() + "^");
                } else {
                    address.append("^");
                }

                xPath = getCustomXPath();
                nodes = (NodeList) xPath.evaluate(
                        "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:addr/hl7:state",
                        doc.getDocumentElement(), XPathConstants.NODESET);
                if (nodes.getLength() > 0) {
                    address.append(((Element) nodes.item(0)).getTextContent() + "^");
                } else {
                    address.append("^");
                }

                xPath = getCustomXPath();
                nodes = (NodeList) xPath.evaluate(
                        "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:addr/hl7:postalCode",
                        doc.getDocumentElement(), XPathConstants.NODESET);
                if (nodes.getLength() > 0) {
                    address.append(((Element) nodes.item(0)).getTextContent() + "^");
                } else {
                    address.append("^");
                }

                xPath = getCustomXPath();
                nodes = (NodeList) xPath.evaluate(
                        "/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:addr/hl7:country",
                        doc.getDocumentElement(), XPathConstants.NODESET);
                if (nodes.getLength() > 0) {
                    address.append(((Element) nodes.item(0)).getTextContent());
                } else {
                    address.append("^");
                }

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

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

        // Create rim:Name if necessary...
        //         xPath = XPathFactory.newInstance().newXPath();
        //         nodes = (NodeList)xPath.evaluate("/ClinicalDocument/title",
        //                 doc.getDocumentElement(),
        //                 XPathConstants.NODESET);
        //         if (nodes.getLength() > 0)
        //         {
        //            InternationalStringType docName = new InternationalStringType();
        //            LocalizedStringType localizedName = new LocalizedStringType();
        //            localizedName.setValue(((Element)nodes.item(0)).getNodeValue());
        //            docName.getLocalizedString().add(localizedName);
        //            extrinsicObject.setName(docName);
        //         }

        // Create rim:Description if necessary...
        //         xPath = XPathFactory.newInstance().newXPath();
        //         nodes = (NodeList)xPath.evaluate("/ClinicalDocument/comments",
        //                 doc.getDocumentElement(),
        //                 XPathConstants.NODESET);
        //         if (nodes.getLength() > 0)
        //         {
        //            InternationalStringType docComments = new InternationalStringType();
        //            LocalizedStringType localizedComments = new LocalizedStringType();
        //            localizedComments.setValue(((Element)nodes.item(0)).getTextContent());
        //            docComments.getLocalizedString().add(localizedComments);
        //            extrinsicObject.setDescription(docComments);
        //         }

        // Create classifications - start with document author(s)...
        ArrayList<ClassificationType> documentAuthorClassifications = new ArrayList<ClassificationType>();
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:author", doc.getDocumentElement(),
                XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            for (int i = 0; i < nodes.getLength(); ++i) {
                ClassificationType documentAuthorClassification = new ClassificationType();
                documentAuthorClassification.setId(UUID.randomUUID().toString());
                documentAuthorClassification.setClassificationScheme(documentAuthorClassificationScheme);
                documentAuthorClassification.setClassifiedObject(documentId);
                documentAuthorClassification.setNodeRepresentation("");
                slot = new SlotType1();
                slot.setName("authorPerson");

                // authorPerson rim:Slot
                StringBuilder authorName = new StringBuilder();
                xPath = getCustomXPath();
                NodeList subNodes = (NodeList) xPath.evaluate("hl7:assignedAuthor/hl7:assignedPerson",
                        nodes.item(i).getChildNodes(), XPathConstants.NODESET);
                if (subNodes.getLength() > 0) {
                    xPath = getCustomXPath();
                    NodeList assignedPersonSubNodes = (NodeList) xPath.evaluate("hl7:name/hl7:prefix",
                            subNodes.item(0).getChildNodes(), XPathConstants.NODESET);
                    if (assignedPersonSubNodes.getLength() > 0) {
                        authorName.append(((Element) assignedPersonSubNodes.item(0)).getTextContent() + " ");
                    }

                    xPath = getCustomXPath();
                    assignedPersonSubNodes = (NodeList) xPath.evaluate("hl7:name/hl7:given",
                            subNodes.item(0).getChildNodes(), XPathConstants.NODESET);
                    if (assignedPersonSubNodes.getLength() > 0) {
                        authorName.append(((Element) assignedPersonSubNodes.item(0)).getTextContent() + " ");
                    }

                    xPath = getCustomXPath();
                    assignedPersonSubNodes = (NodeList) xPath.evaluate("hl7:name/hl7:family",
                            subNodes.item(0).getChildNodes(), XPathConstants.NODESET);
                    if (assignedPersonSubNodes.getLength() > 0) {
                        authorName.append(((Element) assignedPersonSubNodes.item(0)).getTextContent());
                    }

                    xPath = getCustomXPath();
                    assignedPersonSubNodes = (NodeList) xPath.evaluate("hl7:name/hl7:suffix",
                            subNodes.item(0).getChildNodes(), XPathConstants.NODESET);
                    if (assignedPersonSubNodes.getLength() > 0) {
                        authorName.append(" " + ((Element) assignedPersonSubNodes.item(0)).getTextContent());
                    }
                } else {
                    // If assignedAuthor is not present, then check for representedOrganization/name...
                    subNodes = (NodeList) xPath.evaluate(
                            "hl7:assignedAuthor/hl7:representedOrganization/hl7:name",
                            nodes.item(i).getChildNodes(), XPathConstants.NODESET);
                    xPath = XPathFactory.newInstance().newXPath();
                    if (subNodes.getLength() > 0) {
                        authorName.append(((Element) subNodes.item(0)).getTextContent());
                    }
                }

                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(documentId);
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:code", doc.getDocumentElement(),
                XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            //  from properties file
            classification.setNodeRepresentation(documentClassCodesNodeRepresentation);

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

            if (((Element) nodes.item(0)).getAttribute("codeSystem") != null) {
                valueList = new ValueListType();
                // dynamically from the document or from properties file
                valueList.getValue().add(documentClassCodesCodingScheme);
                slot.setValueList(valueList);
                classification.getSlot().add(slot);
            }

            if (((Element) nodes.item(0)).getAttribute("displayName") != null) {
                InternationalStringType text = new InternationalStringType();
                LocalizedStringType localizedText = new LocalizedStringType();
                // dynamically from the document or from properties file
                localizedText.setValue(documentClassCodesName);
                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(documentId);
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:confidentialityCode",
                doc.getDocumentElement(), XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            if (((Element) nodes.item(0)).getAttribute("code") != null) {
                classification.setNodeRepresentation(((Element) nodes.item(0)).getAttribute("code"));
            }

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

            if (((Element) nodes.item(0)).getAttribute("codeSystem") != null) {
                valueList = new ValueListType();
                valueList.getValue().add(((Element) nodes.item(0)).getAttribute("codeSystem"));
                slot.setValueList(valueList);
                classification.getSlot().add(slot);
            }

            if (((Element) nodes.item(0)).getAttribute("displayName") != null) {
                InternationalStringType text = new InternationalStringType();
                LocalizedStringType localizedText = new LocalizedStringType();
                localizedText.setValue(((Element) nodes.item(0)).getAttribute("displayName"));
                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(documentId);
        classification.setNodeRepresentation(documentFormatCodesNodeRepresentation);
        slot = new SlotType1();
        slot.setName("codingScheme");
        valueList = new ValueListType();
        valueList.getValue().add(documentFormatCodesCodingScheme);
        slot.setValueList(valueList);
        classification.getSlot().add(slot);
        InternationalStringType text = new InternationalStringType();
        LocalizedStringType 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(documentId);
        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(documentId);
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:code", doc.getDocumentElement(),
                XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            if (((Element) nodes.item(0)).getAttribute("code") != null) {
                classification.setNodeRepresentation(documentPracticeSettingCodesNodeRepresentation);
            }

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

            if (((Element) nodes.item(0)).getAttribute("codeSystem") != null) {
                valueList = new ValueListType();
                valueList.getValue().add(documentPracticeSettingCodesCodingScheme);
                slot.setValueList(valueList);
                classification.getSlot().add(slot);
            }

            if (((Element) nodes.item(0)).getAttribute("displayName") != null) {
                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(documentId);
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:code", doc.getDocumentElement(),
                XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            if (((Element) nodes.item(0)).getAttribute("code") != null) {
                classification.setNodeRepresentation(((Element) nodes.item(0)).getAttribute("code"));
            }

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

            if (((Element) nodes.item(0)).getAttribute("codeSystem") != null) {
                valueList = new ValueListType();
                valueList.getValue().add(((Element) nodes.item(0)).getAttribute("codeSystem"));
                slot.setValueList(valueList);
                classification.getSlot().add(slot);
            }

            if (((Element) nodes.item(0)).getAttribute("displayName") != null) {
                text = new InternationalStringType();
                localizedText = new LocalizedStringType();
                localizedText.setValue(((Element) nodes.item(0)).getAttribute("displayName"));
                text.getLocalizedString().add(localizedText);
                classification.setName(text);
            }

            extrinsicObject.getClassification().add(classification);
        }

        // Create rim:ExternalIdentifier(s) - first the XDSDocumentEntry.patientId value(s)...
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:recordTarget/hl7:patientRole/hl7:id",
                doc.getDocumentElement(), XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            //            for (int i = 0; i < nodes.getLength(); ++i)
            //            {
            //               ExternalIdentifierType externalIdentifierPatientId = new ExternalIdentifierType();
            //               externalIdentifierPatientId.setId(UUID.randomUUID().toString());
            //               externalIdentifierPatientId.setRegistryObject(documentId);
            //               externalIdentifierPatientId.setIdentificationScheme(ExtrinsicObjectExternalIdentifierPatientIdIdentificationScheme);
            //               externalIdentifierPatientId.setValue(((Element)nodes.item(i)).getAttribute("extension")
            //                     + "^^^&amp;"
            //                     + ((Element)nodes.item(i)).getAttribute("root")
            //                     + "&amp;ISO");
            //               text = new InternationalStringType();
            //               localizedText = new LocalizedStringType();
            //               localizedText.setValue(ExtrinsicObjectExternalIdentifierPatientIdName);
            //               text.getLocalizedString().add(localizedText);
            //               externalIdentifierPatientId.setName(text);
            //               extrinsicObject.getExternalIdentifier().add(externalIdentifierPatientId);
            //            }

            ExternalIdentifierType externalIdentifierPatientId = new ExternalIdentifierType();
            externalIdentifierPatientId.setId(UUID.randomUUID().toString());
            externalIdentifierPatientId.setRegistryObject(documentId);
            externalIdentifierPatientId
                    .setIdentificationScheme(extrinsicObjectExternalIdentifierPatientIdIdentificationScheme);
            externalIdentifierPatientId.setValue(((Element) nodes.item(0)).getAttribute("extension") + "^^^&"
                    + ((Element) nodes.item(0)).getAttribute("root") + "&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)...
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:id", doc.getDocumentElement(),
                XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            //            for (int i = 0; i < nodes.getLength(); ++i)
            //            {
            //               ExternalIdentifierType externalIdentifierPatientId = new ExternalIdentifierType();
            //               externalIdentifierPatientId.setId(UUID.randomUUID().toString());
            //               externalIdentifierPatientId.setRegistryObject(documentId);
            //               externalIdentifierPatientId.setIdentificationScheme(ExtrinsicObjectExternalIdentifierUniqueIdIdentificationScheme);
            //               externalIdentifierPatientId.setValue(((Element)nodes.item(i)).getAttribute("root"));
            //               text = new InternationalStringType();
            //               localizedText = new LocalizedStringType();
            //               localizedText.setValue(ExtrinsicObjectExternalIdentifierUniqueIdName);
            //               text.getLocalizedString().add(localizedText);
            //               externalIdentifierPatientId.setName(text);
            //               extrinsicObject.getExternalIdentifier().add(externalIdentifierPatientId);
            //            }

            ExternalIdentifierType externalIdentifierDocumentId = new ExternalIdentifierType();
            externalIdentifierDocumentId.setId(UUID.randomUUID().toString());
            externalIdentifierDocumentId.setRegistryObject(documentId);
            externalIdentifierDocumentId
                    .setIdentificationScheme(extrinsicObjectExternalIdentifierUniqueIdIdentificationScheme);

            if (testMode) {
                DateTime testDocId = DateTime.now(DateTimeZone.UTC);
                externalIdentifierDocumentId
                        .setValue(((Element) nodes.item(0)).getAttribute("root") + "^" + testDocId.getMillis());
            } else {
                externalIdentifierDocumentId.setValue(((Element) nodes.item(0)).getAttribute("root") + "^"
                        + ((Element) nodes.item(0)).getAttribute("extension"));
            }

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

        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);
        xPath = getCustomXPath();
        nodes = (NodeList) xPath.evaluate("/hl7:ClinicalDocument/hl7:code", doc.getDocumentElement(),
                XPathConstants.NODESET);
        if (nodes.getLength() > 0) {
            if (((Element) nodes.item(0)).getAttribute("code") != null) {
                classification.setNodeRepresentation(((Element) nodes.item(0)).getAttribute("code"));
            }

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

            if (((Element) nodes.item(0)).getAttribute("codeSystem") != null) {
                valueList = new ValueListType();
                valueList.getValue().add(((Element) nodes.item(0)).getAttribute("codeSystem"));
                slot.setValueList(valueList);
                classification.getSlot().add(slot);
            }

            if (((Element) nodes.item(0)).getAttribute("displayName") != null) {
                text = new InternationalStringType();
                localizedText = new LocalizedStringType();
                localizedText.setValue(((Element) nodes.item(0)).getAttribute("displayName"));
                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(documentId);
        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));

        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(cdaDocument);
        documentForMessage.setId(documentId);
        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 + documentId + "_ProvideAndRegisterDocumentSetRequest.xml"),
                    requestElement.toString().getBytes());
        }

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

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

License:Apache License

/**
 * @param contract//from   w  w w. j a va 2s . co m
 * @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.ja v  a 2s .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  .java2  s  .com

    return ec.addResult(this, dateObject);
}

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

License:Apache License

/**
 * Build the aggregation {@link DataTable}
 *//*from w  w w . j a va2 s  . com*/
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.blackboardvcportlet.service.SessionForm.java

License:Apache License

public void setStartTime(DateTime startTime) {
    startDate = startTime.toDateMidnight();
    startHour = startTime.getHourOfDay();
    startMinute = startTime.getMinuteOfHour();
    startHourMinute = new LocalTime(startTime);
}

From source file:org.jasig.portlet.blackboardvcportlet.service.SessionForm.java

License:Apache License

public void setEndTime(DateTime endTime) {
    endDate = endTime.toDateMidnight();/*from w ww  .j  a va  2 s.c  o m*/
    endHour = endTime.getHourOfDay();
    endMinute = endTime.getMinuteOfHour();
    endHourMinute = new LocalTime(endTime);
}

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

License:Apache License

/**
 * Get an XMLGregorianCalendar for the specified date.
 *
 * @param date//www  . ja v  a2s .  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;
}