Example usage for javax.xml.bind JAXBElement JAXBElement

List of usage examples for javax.xml.bind JAXBElement JAXBElement

Introduction

In this page you can find the example usage for javax.xml.bind JAXBElement JAXBElement.

Prototype

public JAXBElement(QName name, Class<T> declaredType, T value) 

Source Link

Document

Construct an xml element instance.

Usage

From source file:org.jboss.jopr.tool.jbas5.PluginDescriptorGenerator.java

private static JAXBElement<? extends ConfigurationProperty> getJAXBElement(ConfigurationProperty configProp) {
    JAXBElement<? extends ConfigurationProperty> propElement;
    QName qname;//from   ww w  .j av a 2s. c  o  m
    if (configProp instanceof SimpleProperty)
        qname = SIMPLE_PROPERTY_QNAME;
    else if (configProp instanceof ListProperty)
        qname = LIST_PROPERTY_QNAME;
    else if (configProp instanceof MapProperty)
        qname = MAP_PROPERTY_QNAME;
    else
        throw new IllegalStateException();
    propElement = new JAXBElement(qname, configProp.getClass(), configProp);
    return propElement;
}

From source file:org.jembi.rhea.transformers.XDSRepositoryProvideAndRegisterDocument.java

protected ProvideAndRegisterDocumentSetRequestType buildRegisterRequest(String oru_r01_request,
        EncounterInfo enc, XDSAffinityDomain domain) {
    ProvideAndRegisterDocumentSetRequestType xdsRequest = new ProvideAndRegisterDocumentSetRequestType();
    SubmitObjectsRequest submissionRequest = new SubmitObjectsRequest();
    RegistryObjectListType registryObjects = new RegistryObjectListType();
    submissionRequest.setRegistryObjectList(registryObjects);
    xdsRequest.setSubmitObjectsRequest(submissionRequest);
    Date now = new Date();

    // For each document
    ExtrinsicObjectType document = XDSUtil.createExtrinsicObject("text/xml", "Physical",
            XdsGuidType.XDSDocumentEntry);

    // To add slots
    document.getSlot().add(XDSUtil.createSlot("creationTime", formatter_yyyyMMdd.format(now)));
    document.getSlot().add(XDSUtil.createSlot("languageCode", "en-us"));
    document.getSlot().add(XDSUtil.createSlot("serviceStartTime", enc.getEncounterDateTime()));
    document.getSlot().add(XDSUtil.createSlot("serviceStopTime", enc.getEncounterDateTime()));
    document.getSlot().add(XDSUtil.createSlot("sourcePatientId", enc.getPID()));
    document.getSlot()//  w w w.  ja  v  a2s.c  o m
            .add(XDSUtil.createSlot("sourcePatientInfo", "PID-3|" + enc.getPID(), "PID-5|" + enc.getName()));
    //if (domain.getRepositoryUniqueId()!=null)
    //   document.getSlot().add(XDSUtil.createSlot("repositoryUniqueId", domain.getRepositoryUniqueId()));
    //if (domain.getHomeCommunityId()!=null)
    //   document.getSlot().add(XDSUtil.createSlot("homeCommunityId", domain.getHomeCommunityId()));

    // To add classifications
    SlotType1[] authorSlots = new SlotType1[] { XDSUtil.createSlot("authorPerson", enc.getAttendingDoctor()),
            XDSUtil.createSlot("authorInstitution", enc.getLocation()), };
    document.getClassification().add(
            XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_Author, "", null, authorSlots));

    SlotType1[] classCodeSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getClassCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_ClassCode,
                    domain.getClassCode().getCode(), domain.getClassCode().getDisplay(), classCodeSlots));

    SlotType1[] confidentialitySlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getConfidentialityCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_ConfidentialityCode,
                    domain.getConfidentialityCode().getCode(), domain.getConfidentialityCode().getDisplay(),
                    confidentialitySlots));

    // To add external ids
    document.getExternalIdentifier().add(
            XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSDocumentEntry_PatientId, enc.getPID()));
    String docUniqueId = String.format("%s.%s.%s", systemSourceID, "1",
            new SimpleDateFormat("yyyy.MM.dd.ss.SSS").format(now));
    document.getExternalIdentifier().add(
            XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSDocumentEntry_UniqueId, docUniqueId));

    // Add to list of objects
    registryObjects.getIdentifiable()
            .add(new JAXBElement<ExtrinsicObjectType>(
                    new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "ExtrinsicObject"),
                    ExtrinsicObjectType.class, document));

    //TODO eventCodeList

    // Create submission set
    RegistryPackageType pkg = XDSUtil.createRegistryPackage();
    pkg.getSlot().add(XDSUtil.createSlot("submissionTime", formatter_yyyyMMdd.format(now)));

    // To add classifications
    SlotType1[] contentTypeSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getContentTypeCode().getCodingScheme()) };
    pkg.getClassification().add(XDSUtil.createClassification(pkg, XdsGuidType.XDSSubmissionSet_ContentType,
            domain.getContentTypeCode().getCode(), domain.getContentTypeCode().getDisplay(), contentTypeSlots));

    SlotType1[] formatSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getFormatCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_FormatCode,
                    domain.getFormatCode().getCode(), domain.getFormatCode().getDisplay(), formatSlots));

    SlotType1[] healthcareFacilityTypeSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getHealthcareFacilityTypeCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_HealthcareFacilityCode,
                    domain.getHealthcareFacilityTypeCode().getCode(),
                    domain.getHealthcareFacilityTypeCode().getDisplay(), healthcareFacilityTypeSlots));

    SlotType1[] practiceSettingSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getPracticeSettingCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_PracticeSettingCode,
                    domain.getPracticeSettingCode().getCode(), domain.getPracticeSettingCode().getDisplay(),
                    practiceSettingSlots));

    SlotType1[] typeSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getTypeCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_TypeCode,
                    domain.getTypeCode().getCode(), domain.getTypeCode().getDisplay(), typeSlots));

    // To add external ids
    pkg.getExternalIdentifier().add(
            XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSSubmissionSet_PatientId, enc.getPID()));
    _uniqueId = String.format("%s.%s.%s", systemSourceID, "2",
            new SimpleDateFormat("yyyy.MM.dd.ss.SSS").format(now));
    pkg.getExternalIdentifier()
            .add(XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSSubmissionSet_UniqueId, _uniqueId));
    pkg.getExternalIdentifier().add(
            XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSSubmissionSet_SourceId, systemSourceID));

    // Add package to submission
    registryObjects.getIdentifiable()
            .add(new JAXBElement<RegistryPackageType>(
                    new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "RegistryPackage"),
                    RegistryPackageType.class, pkg));

    // Add classification for state
    registryObjects.getIdentifiable().add(new JAXBElement<ClassificationType>(
            new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Classification"),
            ClassificationType.class, XDSUtil.createNodeClassification(pkg, XdsGuidType.XDSSubmissionSet)));

    // Add association
    registryObjects.getIdentifiable()
            .add(new JAXBElement<AssociationType1>(
                    new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Association"),
                    AssociationType1.class, XDSUtil.createAssociation(pkg, document, "Original",
                            "urn:oasis:names:tc:ebxml-regrep:AssociationType:HasMember")));

    // Add document
    Document content = new Document();
    content.setId(document.getId());
    content.setValue(
            new DataHandler(new ByteArrayDataSource(oru_r01_request.getBytes(), "application/octet-stream")));
    xdsRequest.getDocument().add(content);

    return xdsRequest;
}

From source file:org.kitodo.dataformat.access.DivXmlElementAccess.java

/**
 * Creates a meta-data section of the specified domain of the Kitodo type
 * and returns it with its connection to the METS if there is data for it.
 *
 * @param domain//from   w w  w  . j  av a 2 s.  c  o  m
 *            Domain for which a metadata section is to be generated
 * @return a metadata section, if there is data for it
 */
static Optional<MdSecType> createMdSec(Iterable<Metadata> metadata, MdSec domain) {
    KitodoType kitodoType = new KitodoType();
    for (Metadata entry : metadata) {
        if (domain.equals(entry.getDomain())) {
            if (entry instanceof MetadataEntry) {
                kitodoType.getMetadata().add(new MetadataXmlElementAccess((MetadataEntry) entry).toMetadata());
            } else if (entry instanceof MetadataGroup) {
                kitodoType.getMetadataGroup()
                        .add(new MetadataGroupXmlElementAccess((MetadataGroup) entry).toXMLMetadataGroup());
            }
        }
    }
    if (kitodoType.getMetadata().isEmpty() && kitodoType.getMetadataGroup().isEmpty()) {
        return Optional.empty();
    } else {
        XmlData xmlData = new XmlData();
        xmlData.getAny().add(new JAXBElement<>(KITODO_QNAME, KitodoType.class, kitodoType));
        MdWrap mdWrap = new MdWrap();
        mdWrap.setXmlData(xmlData);
        MdSecType dmdSec = new MdSecType();
        dmdSec.setMdWrap(mdWrap);
        return Optional.of(dmdSec);
    }
}

From source file:org.multicore_association.measure.mem.writeback.SetResultToShim.java

/**
 * Set the value to read the existing SHIM file.
 * @return Flag for success judgements//from w  w  w  .  j  ava 2 s.  com
 * @throws ShimFileFormatException
 * @throws ShimFileGenerateException
 */
private static boolean appendToExistingShim() {
    /*
     * append to existing llvm-shim
     */
    SystemConfiguration sysConf = null;

    try {
        JAXBContext context = JAXBContext.newInstance(SystemConfiguration.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            unmarshaller.setSchema(schema);
            unmarshaller.setEventHandler(new ValidationEventHandler() {
                @Override
                public boolean handleEvent(ValidationEvent event) {
                    if ((event.getSeverity() == ValidationEvent.FATAL_ERROR)
                            || (event.getSeverity() == ValidationEvent.ERROR)) {
                        ValidationEventLocator loc = event.getLocator();
                        parseErrList.add("    Line[" + loc.getLineNumber() + "] : " + event.getMessage());
                    }
                    return true;
                }
            });
        }

        sysConf = unmarshaller.unmarshal(new StreamSource(shimf), SystemConfiguration.class).getValue();

        if (parseErrList.size() > 0) {
            System.err.println("Error: input SHIM file validation error");

            System.err.println("    Validation error location:");
            for (int i = 0; i < parseErrList.size(); i++) {
                System.err.println(parseErrList.get(i));
            }
            return false;
        }
    } catch (Exception e) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        e.printStackTrace();
        return false;
    }

    AddressSpaceSet addrSpaceSet = sysConf.getAddressSpaceSet();
    if (addrSpaceSet == null) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    List<AddressSpace> addrSpaceList = addrSpaceSet.getAddressSpace();
    if (addrSpaceList == null) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    masterComponentMap = new HashMap<String, MasterComponent>();
    slaveComponentMap = new HashMap<String, SlaveComponent>();
    accessTypeMap = new HashMap<String, AccessType>();

    List<String> route = new ArrayList<String>();
    ComponentSet cs = sysConf.getComponentSet();
    route.add(cs.getName());

    makeRefMapFromComponentSet(cs, route);

    for (int i = 0; i < measureList.size(); i++) {
        MeasurementsCSVData data = measureList.get(i);

        route.clear();

        /*
         * search AddressSpaceName
         */
        AddressSpace addrSp = null;
        for (Iterator<AddressSpace> j = addrSpaceList.iterator(); j.hasNext();) {
            AddressSpace as = j.next();

            if (as.getName() != null && as.getName().equals(data.getAddressSpaceName())) {
                addrSp = as;
                break;
            }
        }
        if (addrSp == null) {
            System.err.println("Error: Unknown 'Address Space' name (\"" + data.getAddressSpaceName() + "\").");
            return false;
        }

        route.add(addrSp.getName());

        /*
         * search SubSpaceName
         */
        SubSpace subSp = null;
        List<SubSpace> ssList = addrSp.getSubSpace();
        for (Iterator<SubSpace> j = ssList.iterator(); j.hasNext();) {
            SubSpace ss = j.next();

            route.add(ss.getName());
            String path = createPathName(route);
            route.remove(ss.getName());
            if (path != null && path.equals(data.getSubSpaceName())) {
                subSp = ss;
                break;
            }

        }
        if (subSp == null) {
            System.err.println("Error: Unknown 'Sub Space' name (\"" + data.getSubSpaceName() + "\").");
            return false;
        }

        /*
         * search SlaveComponentRef in MasterSlaveBinding
         */
        MasterSlaveBindingSet msBindSet = null;
        msBindSet = subSp.getMasterSlaveBindingSet();
        if (msBindSet == null) {
            continue;
        }

        MasterSlaveBinding msBind = null;
        List<MasterSlaveBinding> msBindList = msBindSet.getMasterSlaveBinding();
        SlaveComponent scComp = slaveComponentMap.get(data.getSlaveComponentName());
        if (scComp == null) {
            System.err.println(
                    "Error: Unknown 'Slave Comonent' name (\"" + data.getSlaveComponentName() + "\").");
            return false;
        }
        for (Iterator<MasterSlaveBinding> j = msBindList.iterator(); j.hasNext();) {
            MasterSlaveBinding msb = j.next();
            SlaveComponent sca = (SlaveComponent) msb.getSlaveComponentRef();

            if (sca != null && sca.getId().equals(scComp.getId())) {
                msBind = msb;
                break;
            }
        }
        if (msBind == null) {
            continue;
        }

        /*
         * search MasterComponentRef in Accessor
         */
        Accessor accessor = null;
        List<Accessor> acList = msBind.getAccessor();
        MasterComponent mcComp = masterComponentMap.get(data.getMasterComponentName());
        if (mcComp == null) {
            System.err.println(
                    "Error: Unknown 'Master Comonent' name (\"" + data.getMasterComponentName() + "\").");
            return false;
        }
        for (Iterator<Accessor> j = acList.iterator(); j.hasNext();) {
            Accessor ac = j.next();
            MasterComponent mc = (MasterComponent) ac.getMasterComponentRef();

            if (mc != null && mc.getId().equals(mcComp.getId())) {
                accessor = ac;
                break;
            }
        }
        if (accessor == null) {
            continue;
        }

        /*
         * search PerformanceSet
         */
        PerformanceSet perfrmSet = null;

        if (accessor.getPerformanceSet().size() != 0) {
            perfrmSet = accessor.getPerformanceSet().get(0);
        }
        if (perfrmSet == null) {
            continue;
        }

        /*
         * search Performance
         */
        List<Performance> pfrmList = perfrmSet.getPerformance();
        AccessType atComp = accessTypeMap.get(data.getAccessTypeName());
        if (atComp == null) {
            System.err.println("Error: Unknown 'Access Type' name (\"" + data.getAccessTypeName() + "\").");
            return false;
        }
        for (Iterator<Performance> j = pfrmList.iterator(); j.hasNext();) {
            Performance pfm = j.next();
            AccessType at = (AccessType) pfm.getAccessTypeRef();

            if (at != null && at.getId().equals(atComp.getId())) {
                Latency latency = new Latency();
                Pitch pitch = new Pitch();

                latency.setBest(data.getBestLatency());
                latency.setWorst(data.getWorstLatency());
                latency.setTypical(data.getTypicalLatency());
                pitch.setBest(data.getBestPitch());
                pitch.setWorst(data.getWorstPitch());
                pitch.setTypical(data.getTypicalPitch());

                pfm.setLatency(latency);
                pfm.setPitch(pitch);
                break;
            }
        }
    }

    try {
        JAXBContext context = JAXBContext.newInstance(SystemConfiguration.class.getPackage().getName());

        Marshaller marshaller = context.createMarshaller();
        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            marshaller.setSchema(schema);
        }
        QName qname = new QName("", "SystemConfiguration");

        JAXBElement<SystemConfiguration> elem = new JAXBElement<SystemConfiguration>(qname,
                SystemConfiguration.class, sysConf);

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        //         marshaller.marshal(elem, new PrintStream(shimf));
        marshaller.marshal(elem, System.out);
    } catch (JAXBException e) {
        e.printStackTrace();
        System.err.println("Error: exception occurs in SHIM file generation"); //$NON-NLS-1$
        return false;
    } catch (SAXException e) {
        e.printStackTrace();
        System.err.println("Error: output SHIM file validation error"); //$NON-NLS-1$
        return false;
    }

    return true;
}

From source file:org.netbeans.jbatch.modeler.specification.model.job.util.JobUtil.java

public void saveModelerFile(ModelerFile modelerFile) {

    Definitions definitions = (Definitions) modelerFile.getDefinitionElement();

    try {/*w w  w. ja  va  2 s . c o m*/
        updateBatchDiagram(modelerFile);
        List<String> closeDefinitionIdList = closeDiagram(modelerFile, definitions.getGarbageDefinitions());
        List<String> definitionIdList = new ArrayList<String>(closeDefinitionIdList);
        //            definitionIdList.addAll(definitions.getGarbageDefinitions());
        definitionIdList.add(definitions.getId());
        File savedFile = modelerFile.getFile();

        BufferedReader br = new BufferedReader(new FileReader(savedFile));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("savedFile : " + line);
        }

        File cloneSavedFile = File.createTempFile("TMP", "job");
        FileUtils.copyFile(savedFile, cloneSavedFile);
        //            br = new BufferedReader(new FileReader(cloneSavedFile));
        //            line = null;
        //            while ((line = br.readLine()) != null) {
        //                System.out.println("line2 : " + line);
        //            }

        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile));
        xsw.setDefaultNamespace("http://jbatchsuite.java.net");

        xsw.writeStartDocument();
        xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net");
        xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee");
        xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net");
        xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270");
        xsw.writeNamespace("nbm", "http://nbmodeler.java.net");

        //            br = new BufferedReader(new FileReader(savedFile));
        //            line = null;
        //            while ((line = br.readLine()) != null) {
        //                System.out.println("line3 : " + line);
        //            }
        if (cloneSavedFile.length() != 0) {
            try {
                XMLInputFactory xif = XMLInputFactory.newFactory();
                StreamSource xml = new StreamSource(cloneSavedFile);
                XMLStreamReader xsr = xif.createXMLStreamReader(xml);
                xsr.nextTag();
                while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
                    //                        Def   Y    N
                    //                        Tag   N(D) Y(D)
                    //                        ________________
                    //                              T    T
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(S) N(S)
                    //                        ________________
                    //                              S    S
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(D) N(S)
                    //                        ________________
                    //                              T    S
                    //                        ----------------
                    //
                    //                       (D) => Different
                    //                       (S) => Same
                    //                        Y => Id Exist
                    //                        N => Id is null
                    //                        T => Transform
                    //                        S => Skip

                    if (xsr.getLocalName().equals("definitions")) {
                        //                            if (definitions.getId() == null) {
                        //                                if (xsr.getAttributeValue(null, "id") != null) {
                        //                                    transformXMLStream(xsr, xsw);
                        //                                } else {
                        //                                    skipXMLStream(xsr);
                        //                                }
                        //                            } else {
                        if (xsr.getAttributeValue(null, "id") == null) {
                            if (definitions.getId() == null) {
                                skipXMLStream(xsr);
                            } else {
                                transformXMLStream(xsr, xsw);
                            }
                        } else {
                            if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) {
                                transformXMLStream(xsr, xsw);
                            } else {
                                skipXMLStream(xsr);
                            }
                        }
                        //                            }
                    }
                    xsr.nextTag();
                }
            } catch (XMLStreamException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        JAXBElement<Definitions> je = new JAXBElement<Definitions>(
                new QName("http://jbatchsuite.java.net", "definitions", "jbatchnb"), Definitions.class,
                definitions);
        if (jobContext == null) {
            jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class });
        }
        if (jobMarshaller == null) {
            jobMarshaller = jobContext.createMarshaller();
        }

        // output pretty printed
        jobMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jobMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        //          jobMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.omg.org/spec/Batch/20100524/MODEL http://www.omg.org/spec/Batch/2.0/20100501/Batch20.xsd");
        jobMarshaller.setEventHandler(new ValidateJAXB());
        jobMarshaller.marshal(je, System.out);
        jobMarshaller.marshal(je, xsw);

        //            xsw.writeEndElement();
        xsw.writeEndDocument();
        xsw.close();

        //            StringWriter sw = new StringWriter();
        //            jobMarshaller.marshal(file.getDefinitionElement(), sw);
        //            FileUtils.writeStringToFile(savedFile, sw.toString().replaceFirst("xmlns:ns[A-Za-z\\d]{0,3}=\"http://www.omg.org/spec/Batch/20100524/MODEL\"",
        //                    "xmlns=\"http://www.omg.org/spec/Batch/20100524/MODEL\""));
    } catch (JAXBException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }

}

From source file:org.openengsb.core.common.remote.XmlMethodCallMarshalOutgoingFilter.java

private Document serializeRequest(MethodCallMessage result) {
    DOMResult domResult = new DOMResult();
    try {//from  w ww.j a va  2s  .com
        @SuppressWarnings("unchecked")
        List<Class<?>> classes = ClassUtils.convertClassNamesToClasses(result.getMethodCall().getClasses());
        if (classes.contains(null)) {
            throw new FilterException("Could not load all required classes. Require: "
                    + result.getMethodCall().getClasses() + " got: " + classes);
        }
        classes.add(MethodCallMessage.class);
        JAXBContext jaxbContext = JAXBContext.newInstance(classes.toArray(new Class<?>[classes.size()]));
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller
                .marshal(new JAXBElement<MethodCallMessage>(new QName(MethodCallMessage.class.getSimpleName()),
                        MethodCallMessage.class, result), domResult);
    } catch (JAXBException e) {
        throw new FilterException(e);
    }
    return (Document) domResult.getNode();
}

From source file:org.openhie.openempi.nhinadapter.hl7.Hl7ConversionHelper.java

private JAXBElement<PRPAMT201310UV02Person> createPatientPersonFromPerson(Person person,
        PRPAIN201305UV02 request) {//  w  w w . jav  a 2s.  c  om
    PRPAMT201310UV02Person thePerson = new PRPAMT201310UV02Person();
    PNExplicit name = Utilities.generatePnExplicit(person.getGivenName(), person.getFamilyName());
    thePerson.getName().add(name);
    thePerson
            .setAdministrativeGenderCode(Utilities.generateCe(getAdministrativeGenderCode(person.getGender())));
    thePerson.setBirthTime(Utilities.generateTSExplicit(person.getDateOfBirth()));

    // If the adapter is configured to return the phone number and we have, it add it to the message.
    if (allowTelecomResponseAttribute && person.getPhoneNumber() != null) {
        thePerson.getTelecom().add(Utilities.generateTELExplicit(person));
    }

    // If the adapter is configured to return the address and we have it, add it to the message
    if (allowAddressResponseAttribute) {
        ADExplicit address = Utilities.generateADExplicit(person.getAddress1(), person.getCity(),
                person.getState(), person.getPostalCode());
        if (address != null) {
            thePerson.getAddr().add(address);
        }
    }

    if (allowSocialSecurityNumberResponseAttribute && Utilities.isNotNullish(person.getSsn())) {
        thePerson.getAsOtherIDs().add(generateSsnAsOtherId(person));
    }

    javax.xml.namespace.QName xmlqname = new javax.xml.namespace.QName("urn:hl7-org:v3", "patientPerson");
    JAXBElement<PRPAMT201310UV02Person> jaxbPerson = new JAXBElement<PRPAMT201310UV02Person>(xmlqname,
            PRPAMT201310UV02Person.class, thePerson);

    return jaxbPerson;
}

From source file:org.openhie.openempi.nhinadapter.hl7.Utilities.java

public static MCCIMT000300UV01Receiver generateMCCIMT00300UV01Receiver(MCCIMT000100UV01Sender sender) {

    MCCIMT000300UV01Receiver receiver = new MCCIMT000300UV01Receiver();
    II oid = null;// www .  j av  a  2  s.  c om

    receiver.setTypeCode(CommunicationFunctionType.RCV);

    if (sender.getDevice() != null && sender.getDevice().getAsAgent() != null
            && sender.getDevice().getAsAgent().getValue() != null
            && sender.getDevice().getAsAgent().getValue().getRepresentedOrganization() != null
            && sender.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue() != null
            && isNotNullish(
                    sender.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue().getId())
            && sender.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue().getId()
                    .get(0) != null
            && isNotNullish(sender.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue()
                    .getId().get(0).getRoot())) {
        oid = sender.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue().getId().get(0);
    }

    String senderDeviceIdRoot = "1.2.345.678.999";
    if (sender.getDevice() != null && sender.getDevice().getId() != null
            && sender.getDevice().getId().size() > 0 && sender.getDevice().getId().get(0) != null
            && sender.getDevice().getId().get(0).getRoot() != null) {
        senderDeviceIdRoot = sender.getDevice().getId().get(0).getRoot();
    }

    MCCIMT000300UV01Device receiverDevice = new MCCIMT000300UV01Device();
    receiverDevice.setClassCode(EntityClassDevice.DEV);
    receiverDevice.setDeterminerCode(ConversionConstants.ENTITY_DETERMINER_CODE_INSTANCE);
    log.debug("Setting receiver application to " + senderDeviceIdRoot);
    receiverDevice.getId().add(generateHl7Id(senderDeviceIdRoot, null));

    MCCIMT000300UV01Agent agent = new MCCIMT000300UV01Agent();
    MCCIMT000300UV01Organization org = new MCCIMT000300UV01Organization();
    org.setClassCode(ConversionConstants.ENTITY_CLASS_CODE_ORG);
    org.setDeterminerCode(ConversionConstants.ENTITY_DETERMINER_CODE_INSTANCE);
    org.getId().add(oid);

    javax.xml.namespace.QName xmlqnameorg = new javax.xml.namespace.QName("urn:hl7-org:v3",
            "representedOrganization");
    JAXBElement<MCCIMT000300UV01Organization> orgElem = new JAXBElement<MCCIMT000300UV01Organization>(
            xmlqnameorg, MCCIMT000300UV01Organization.class, org);
    agent.setRepresentedOrganization(orgElem);
    agent.getClassCode().add(ConversionConstants.ROLE_CLASS_AGENT);

    javax.xml.namespace.QName xmlqnameagent = new javax.xml.namespace.QName("urn:hl7-org:v3", "asAgent");
    JAXBElement<MCCIMT000300UV01Agent> agentElem = new JAXBElement<MCCIMT000300UV01Agent>(xmlqnameagent,
            MCCIMT000300UV01Agent.class, agent);

    receiverDevice.setAsAgent(agentElem);
    receiver.setDevice(receiverDevice);
    return receiver;
}

From source file:org.openhie.openempi.nhinadapter.hl7.Utilities.java

public static MCCIMT000300UV01Sender generateMCCIMT00300UV01Sender(List<MCCIMT000100UV01Receiver> receivers) {
    MCCIMT000300UV01Sender sender = new MCCIMT000300UV01Sender();
    if (receivers == null || receivers.size() == 0 || receivers.get(0) == null) {
        log.error("Unable to generate message since receiver entry is missing: " + receivers);
        return sender;
    }/*w  ww.j a  va2s  .  c om*/
    MCCIMT000100UV01Receiver receiver = receivers.get(0);
    sender.setTypeCode(CommunicationFunctionType.SND);

    MCCIMT000300UV01Device device = new MCCIMT000300UV01Device();
    device.setDeterminerCode("INSTANCE");

    II oid = null;
    if (receiver.getDevice() != null && receiver.getDevice().getAsAgent() != null
            && receiver.getDevice().getAsAgent().getValue() != null
            && receiver.getDevice().getAsAgent().getValue().getRepresentedOrganization() != null
            && receiver.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue() != null
            && isNotNullish(receiver.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue()
                    .getId())
            && receiver.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue().getId()
                    .get(0) != null) {
        oid = receiver.getDevice().getAsAgent().getValue().getRepresentedOrganization().getValue().getId()
                .get(0);
    }

    MCCIMT000300UV01Device senderDevice = new MCCIMT000300UV01Device();
    senderDevice.setClassCode(EntityClassDevice.DEV);
    senderDevice.setDeterminerCode(ConversionConstants.ENTITY_DETERMINER_CODE_INSTANCE);
    String receiverDeviceIdRoot = "1.2.345.678.999";
    if (receiver.getDevice() != null && receiver.getDevice().getId() != null
            && receiver.getDevice().getId().size() > 0 && receiver.getDevice().getId().get(0) != null
            && receiver.getDevice().getId().get(0).getRoot() != null) {
        receiverDeviceIdRoot = receiver.getDevice().getId().get(0).getRoot();
    }
    log.debug("Setting sender OID to " + receiverDeviceIdRoot);
    senderDevice.getId().add(generateHl7Id(receiverDeviceIdRoot, null));

    MCCIMT000300UV01Agent agent = new MCCIMT000300UV01Agent();
    MCCIMT000300UV01Organization org = new MCCIMT000300UV01Organization();
    org.setClassCode(ConversionConstants.ENTITY_CLASS_CODE_ORG);
    org.setDeterminerCode(ConversionConstants.ENTITY_DETERMINER_CODE_INSTANCE);
    org.getId().add(oid);

    javax.xml.namespace.QName xmlqnameorg = new javax.xml.namespace.QName("urn:hl7-org:v3",
            "representedOrganization");
    JAXBElement<MCCIMT000300UV01Organization> orgElem = new JAXBElement<MCCIMT000300UV01Organization>(
            xmlqnameorg, MCCIMT000300UV01Organization.class, org);
    agent.setRepresentedOrganization(orgElem);
    agent.getClassCode().add(ConversionConstants.CLASS_CODE_AGENT);

    javax.xml.namespace.QName xmlqnameagent = new javax.xml.namespace.QName("urn:hl7-org:v3", "asAgent");
    JAXBElement<MCCIMT000300UV01Agent> agentElem = new JAXBElement<MCCIMT000300UV01Agent>(xmlqnameagent,
            MCCIMT000300UV01Agent.class, agent);

    senderDevice.setAsAgent(agentElem);
    sender.setDevice(senderDevice);
    return sender;
}

From source file:org.openhie.openempi.openpixpdq.v3.util.Hl7ConversionHelper.java

private static JAXBElement<PRPAMT201310UV02Person> createPatientPersonFromPerson(Patient person,
        PRPAIN201305UV02 request) {/*  www  . ja v  a 2s  .  c o  m*/
    PRPAMT201310UV02Person thePerson = new PRPAMT201310UV02Person();
    PNExplicit name = Utilities.generatePnExplicit(person.getPatientName().getFirstName(),
            person.getPatientName().getLastName());
    thePerson.getName().add(name);
    if (person.getAdministrativeSex() != null) {
        thePerson
                .setAdministrativeGenderCode(Utilities.generateCe(person.getAdministrativeSex().getCDAValue()));
    }
    if (person.getBirthDateTime() != null) {
        thePerson.setBirthTime(Utilities.generateTSExplicit(person.getBirthDateTime().getTime()));
    }

    // If the adapter is configured to return the phone number and we have, it add it to the message.
    if (allowTelecomResponseAttribute && person.getPhoneNumbers() != null) {
        thePerson.getTelecom().add(Utilities.generateTELExplicit(person));
    }

    // If the adapter is configured to return the address and we have it, add it to the message
    if (allowAddressResponseAttribute) {
        Address addressPerson = person.getAddresses().get(0);
        ADExplicit address = Utilities.generateADExplicit(addressPerson.getAddLine1(),
                addressPerson.getAddCity(), addressPerson.getAddState(), addressPerson.getAddZip());
        if (address != null) {
            thePerson.getAddr().add(address);
        }
    }

    if (allowSocialSecurityNumberResponseAttribute && Utilities.isNotNullish(person.getSsn())) {
        thePerson.getAsOtherIDs().add(generateSsnAsOtherId(person));
    }

    javax.xml.namespace.QName xmlqname = new javax.xml.namespace.QName("urn:hl7-org:v3", "patientPerson");
    JAXBElement<PRPAMT201310UV02Person> jaxbPerson = new JAXBElement<PRPAMT201310UV02Person>(xmlqname,
            PRPAMT201310UV02Person.class, thePerson);

    return jaxbPerson;
}