Example usage for javax.xml.bind Unmarshaller setAttachmentUnmarshaller

List of usage examples for javax.xml.bind Unmarshaller setAttachmentUnmarshaller

Introduction

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

Prototype

void setAttachmentUnmarshaller(AttachmentUnmarshaller au);

Source Link

Document

Associate a context that resolves cid's, content-id URIs, to binary data passed as attachments.

Unmarshal time validation, enabled via #setSchema(Schema) , must be supported even when unmarshaller is performing XOP processing.

Usage

From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java

/**
 * Unmarshal the xml into a JAXB object/*from  w  ww. j av  a 2 s . c o m*/
 * @param inputReader
 * @return
 * @throws JAXBException
 */
public Object unmarshal(XMLStreamReader inputReader) throws JAXBException {

    if (DEBUG_ENABLED) {
        String clsText = (inputReader != null) ? inputReader.getClass().toString() : "null";
        log.debug("unmarshal with inputReader=" + clsText);
    }
    // See the Javadoc of the CustomBuilder interface for a complete explanation of
    // the following two instructions:
    XOPEncodedStream xopEncodedStream = XOPUtils.getXOPEncodedStream(inputReader);
    XMLStreamReader reader = XMLStreamReaderUtils.getOriginalXMLStreamReader(xopEncodedStream.getReader());
    if (DEBUG_ENABLED) {
        String clsText = (reader != null) ? reader.getClass().toString() : "null";
        log.debug("  originalReader=" + clsText);
    }

    // There may be a preferred classloader that should be used
    ClassLoader cl = getClassLoader();

    Unmarshaller u = JAXBUtils.getJAXBUnmarshaller(getJAXBContext(cl));

    // Create an attachment unmarshaller
    AttachmentUnmarshaller aum = createAttachmentUnmarshaller(xopEncodedStream.getMimePartProvider());

    if (aum != null) {
        if (DEBUG_ENABLED) {
            log.debug("Adding JAXBAttachmentUnmarshaller to Unmarshaller");
        }
        u.setAttachmentUnmarshaller(aum);
    }

    Object jaxb = null;

    // Unmarshal into the business object.
    if (getProcessType() == null) {
        jaxb = unmarshalByElement(u, reader); // preferred and always used for
                                              // style=document
    } else {
        jaxb = unmarshalByType(u, reader, getProcessType(), isxmlList(), getConstructionType());
    }

    // Successfully unmarshalled the object
    JAXBUtils.releaseJAXBUnmarshaller(getJAXBContext(cl), u);

    // Don't close the reader.  The reader is owned by the caller, and it
    // may contain other xml instance data (other than this JAXB object)
    // reader.close();
    return jaxb;
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * Release Unmarshaller Do not call this method if an exception occurred while using the
 * Unmarshaller. We object my be in an invalid state.
 *
 * @param context      JAXBContext// w w  w  .  j a v  a2 s.  com
 * @param unmarshaller Unmarshaller
 */
public static void releaseJAXBUnmarshaller(JAXBContext context, Unmarshaller unmarshaller) {
    if (log.isDebugEnabled()) {
        log.debug("Unmarshaller placed back into pool");
    }
    if (ENABLE_UNMARSHALL_POOLING) {
        unmarshaller.setAttachmentUnmarshaller(null);
        upool.put(context, unmarshaller);
    }
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java

public void readMessage(InMessage message, MessageContext context) throws XFireFault {
    if (this.requestInfo == null) {
        throw new XFireFault("Unable to read message: no request info was found!", XFireFault.RECEIVER);
    }//from  www .  ja v a  2 s .  c o m

    Object bean;
    try {
        Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller();
        XMLStreamReader streamReader = message.getXMLStreamReader();
        if (this.requestInfo.isSchemaValidate()) {
            try {
                TransformerFactory xformFactory = TransformerFactory.newInstance();
                DOMResult domResult = new DOMResult();
                xformFactory.newTransformer().transform(new StAXSource(streamReader, true), domResult);
                unmarshaller.getSchema().newValidator().validate(new DOMSource(domResult.getNode()));
                streamReader = XMLInputFactory.newInstance()
                        .createXMLStreamReader(new DOMSource(domResult.getNode()));
            } catch (Exception e) {
                throw new XFireRuntimeException("Unable to validate the request against the schema.");
            }
        }
        unmarshaller.setEventHandler(getValidationEventHandler());
        unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshaller(context));
        bean = unmarshaller.unmarshal(streamReader, this.requestInfo.getBeanClass()).getValue();
    } catch (JAXBException e) {
        throw new XFireRuntimeException("Unable to unmarshal type.", e);
    }

    List<Object> parameters = new ArrayList<Object>();
    if (this.requestInfo.isBare()) {
        //bare method, doesn't need to be unwrapped.
        parameters.add(bean);
    } else {
        for (PropertyDescriptor descriptor : this.requestInfo.getPropertyOrder()) {
            try {
                parameters.add(descriptor.getReadMethod().invoke(bean));
            } catch (IllegalAccessException e) {
                throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                        + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER);
            } catch (InvocationTargetException e) {
                throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                        + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER);
            }
        }
    }

    message.setBody(parameters);
}

From source file:org.paxle.core.doc.impl.BasicDocumentFactory.java

public <Doc> Doc unmarshal(InputStream input, Map<String, DataHandler> attachments) throws IOException {
    try {/*from w  w  w .j  ava  2s.  c  o m*/
        final Unmarshaller u = context.createUnmarshaller();
        u.setAdapter(JaxbFileAdapter.class, new JaxbFileAdapter(this.tempFileManager, attachments));
        u.setAdapter(JaxbFieldMapAdapter.class, new JaxbFieldMapAdapter(this.tempFileManager));
        u.setAttachmentUnmarshaller(new JaxbAttachmentUnmarshaller(attachments));
        //         u.setProperty("com.sun.xml.bind.ObjectFactory", new BasicJaxbFactory());

        @SuppressWarnings("unchecked")
        final Doc document = (Doc) u.unmarshal(input);
        return document;
    } catch (JAXBException e) {
        final IOException ioe = new IOException(
                String.format("Unable to unmarshal the document from the stream."));
        ioe.initCause(e);
        throw ioe;
    }
}

From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java

@Override
public Object unmarshal(Source source, @Nullable MimeContainer mimeContainer) throws XmlMappingException {
    source = processSource(source);/*from  w  w  w.  j  a  va  2 s  . c  o m*/

    try {
        Unmarshaller unmarshaller = createUnmarshaller();
        if (this.mtomEnabled && mimeContainer != null) {
            unmarshaller.setAttachmentUnmarshaller(new Jaxb2AttachmentUnmarshaller(mimeContainer));
        }
        if (StaxUtils.isStaxSource(source)) {
            return unmarshalStaxSource(unmarshaller, source);
        } else if (this.mappedClass != null) {
            return unmarshaller.unmarshal(source, this.mappedClass).getValue();
        } else {
            return unmarshaller.unmarshal(source);
        }
    } catch (NullPointerException ex) {
        if (!isSupportDtd()) {
            throw new UnmarshallingFailureException(
                    "NPE while unmarshalling: "
                            + "This can happen due to the presence of DTD declarations which are disabled.",
                    ex);
        }
        throw ex;
    } catch (JAXBException ex) {
        throw convertJaxbException(ex);
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message.//from  w w  w . j a  v  a  2  s  .  c om
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvoke() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish via SOAP attachment
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("application/octet-stream");
    publicationDocument.setDownloadFileName("test.dat");
    byte[] data = new byte[1024 * 256];
    for (int idx = 0; idx < data.length; idx++) {
        data[idx] = 'X';
    }
    DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message./*  ww w  . ja v  a  2s  .c  o m*/
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvokePlainText() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] data = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(data);
    publicationDocument.setEncryptableBinaryContent(null);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxClientTest.java

@Test
public void testGetMessageWithAttachments() throws Exception {
    // STS//from  www . j a v a 2  s .co m
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);
    eHealthBoxClient.getBoxInfo();

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("response message: " + response);

        JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        AttachmentUnmarshaller attachmentUnmarshaller = new SOAPAttachmentUnmarshaller(
                eHealthBoxClient.getMessageAttachments());
        unmarshaller.setAttachmentUnmarshaller(attachmentUnmarshaller);
        JAXBElement<GetFullMessageResponseType> getFullMessageResponseElement = (JAXBElement<GetFullMessageResponseType>) unmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = getFullMessageResponseElement.getValue();
        DataHandler dataHandler = getFullMessageResponse.getMessage().getContentContext().getContent()
                .getDocument().getEncryptableBinaryContent();
        LOG.debug("has data handler: " + (null != dataHandler));
        byte[] data = IOUtils.toByteArray(dataHandler.getInputStream());
        LOG.debug("data: " + new String(data));
    }
}

From source file:test.integ.be.e_contract.mycarenet.ehbox.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message./*from  www .ja  va2  s .com*/
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvoke() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish via SOAP attachment
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("application/octet-stream");
    publicationDocument.setDownloadFileName("test.dat");
    byte[] data = new byte[1024 * 256];
    DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:test.integ.be.e_contract.mycarenet.ehbox.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message./*from  ww w  . j a v a 2 s. c om*/
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvokePlainText() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] data = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(data);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}