Example usage for javax.activation DataSource getInputStream

List of usage examples for javax.activation DataSource getInputStream

Introduction

In this page you can find the example usage for javax.activation DataSource getInputStream.

Prototype

public InputStream getInputStream() throws IOException;

Source Link

Document

This method returns an InputStream representing the data and throws the appropriate exception if it can not do so.

Usage

From source file:org.paxle.core.doc.impl.jaxb.JaxbFileAdapter.java

/**
 * Converts the {@link DataHandler} into a {@link File}.
 * The file is created via the {@link ITempFileManager}.
 *///from ww  w.  j a  v a2s . c  o  m
@Override
public File unmarshal(DataHandler dataHandler) throws Exception {
    if (dataHandler == null)
        return null;

    final DataSource dataSource = dataHandler.getDataSource();
    if (dataSource != null) {
        String cid = null;

        // avoid deserializing a file twice
        for (Entry<String, DataHandler> attachment : attachments.entrySet()) {
            if (attachment.getValue().equals(dataHandler)) {
                cid = attachment.getKey();
                break;
            }
        }

        if (cid != null && this.cidFileMap.containsKey(cid)) {
            return this.cidFileMap.get(cid);
        }

        File tempFile = null;
        InputStream input = null;
        OutputStream output = null;

        try {
            // getting the input stream
            input = dataSource.getInputStream();

            // getting the output stream
            tempFile = this.tempFileManager.createTempFile();
            output = new BufferedOutputStream(new FileOutputStream(tempFile));

            // copy data
            long byteCount = IOUtils.copy(input, output);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug(String.format("%d bytes copied from the data-source into the temp-file '%s'.",
                        Long.valueOf(byteCount), tempFile.getName()));
            }

            if (cid != null) {
                this.cidFileMap.put(cid, tempFile);
            }
            return tempFile;
        } catch (IOException e) {
            this.logger.error(String.format("Unexpected '%s' while loading datasource '%s' (CID=%s).",
                    e.getClass().getName(), dataSource.getName(), cid), e);

            // delete the temp file on errors
            if (tempFile != null && this.tempFileManager.isKnown(tempFile)) {
                this.tempFileManager.releaseTempFile(tempFile);
            }

            // re-throw exception
            throw e;
        } finally {
            // closing streams
            if (input != null)
                input.close();
            if (output != null)
                output.close();
        }
    }
    return null;
}

From source file:org.pentaho.platform.plugin.action.jfreereport.JFreeReportComponent.java

private PentahoTableDataFactory getJarDataFactory() throws Exception {
    PentahoTableDataFactory factory = null;
    JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
    try {//  w  w  w  .  ja v  a2s . com
        org.pentaho.actionsequence.dom.IActionResource actionResource = jFreeReportAction.getDataJar().getJar();
        if (actionResource != null) {
            DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(
                    actionResource.getDataSource());
            InputStream in = dataSource.getInputStream();
            try {
                // not being able to read a single char is definitly a big boo ..
                if (in.read() == -1) {
                    throw new Exception(Messages.getInstance()
                            .getErrorString("JFreeReport.ERROR_0009_REPORT_JAR_UNREADABLE")); //$NON-NLS-1$
                } else {
                    final ClassLoader loader = ReportUtils.createJarLoader(getSession(),
                            getResource(actionResource.getName()));
                    if (loader == null) {
                        throw new Exception(Messages.getInstance()
                                .getString("JFreeReportDataComponent.ERROR_0035_COULD_NOT_CREATE_CLASSLOADER")); //$NON-NLS-1$
                    } else if (!isDefinedInput(AbstractJFreeReportComponent.DATACOMPONENT_CLASSLOCINPUT)) {
                        throw new Exception(Messages.getInstance()
                                .getErrorString("JFreeReport.ERROR_0012_CLASS_LOCATION_MISSING")); //$NON-NLS-1$
                    } else {
                        // Get input parameters, and set them as properties in the report
                        // object.
                        final ReportParameterValues reportProperties = new ReportParameterValues();
                        IActionInput[] actionInputs = jFreeReportAction.getInputs();
                        for (IActionInput element : actionInputs) {
                            final Object paramValue = element.getValue();
                            if (paramValue instanceof Object[]) {
                                final Object[] values = (Object[]) paramValue;
                                final StringBuffer valuesBuffer = new StringBuffer();
                                // TODO support non-string items
                                for (int z = 0; z < values.length; z++) {
                                    if (z == 0) {
                                        valuesBuffer.append(values[z].toString());
                                    } else {
                                        valuesBuffer.append(',').append(values[z].toString());
                                    }
                                }
                                reportProperties.put(element.getName(), valuesBuffer.toString());
                            } else {
                                reportProperties.put(element.getName(), paramValue);
                            }
                        }

                        final DataFactory dataFactory = new PentahoDataFactory(loader);
                        final TableModel model = dataFactory.queryData(
                                jFreeReportAction.getDataJar().getDataClass(),
                                new ParameterDataRow(reportProperties));

                        factory = new PentahoTableDataFactory(
                                AbstractJFreeReportComponent.DATACOMPONENT_DEFAULTINPUT, model);
                    }
                }
            } catch (Exception e) {
                throw new Exception(
                        Messages.getInstance().getErrorString("JFreeReport.ERROR_0009_REPORT_JAR_UNREADABLE")); //$NON-NLS-1$
            }
        }
    } catch (FileNotFoundException e1) {
        throw new Exception(Messages.getInstance().getErrorString("JFreeReport.ERROR_0010_REPORT_JAR_MISSING", //$NON-NLS-1$
                jFreeReportAction.getDataJar().toString()));
    }
    return factory;
}

From source file:org.pentaho.platform.plugin.action.jfreereport.ReportWizardSpecComponent.java

@SuppressWarnings("deprecation")
public ReportSpec getReportSpec() throws IOException {
    JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
    DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(
            jFreeReportAction.getReportDefinitionDataSource());
    ReportSpec reportSpec = null;//from   w w  w. j  a v  a 2 s.co  m
    reportSpec = loadFromZip(dataSource.getInputStream());
    if (reportSpec == null) {
        dataSource = new ActivationHelper.PentahoStreamSourceWrapper(
                jFreeReportAction.getReportDefinitionDataSource());
        reportSpec = (ReportSpec) CastorUtility.getInstance().readCastorObject(dataSource.getInputStream(),
                ReportSpec.class);
    }
    return reportSpec;
}

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Parses the MimePart to create a DataSource.
 *
 * @param part   the current part to be processed
 * @return the DataSource//from   www  .j  av a 2s .  c om
 * @throws MessagingException creating the DataSource failed
 * @throws IOException        creating the DataSource failed
 */
private static DataSource createDataSource(final MimePart part) throws MessagingException, IOException {
    final DataHandler dataHandler = part.getDataHandler();
    final DataSource dataSource = dataHandler.getDataSource();
    final String contentType = getBaseMimeType(dataSource.getContentType());
    final byte[] content = MimeMessageParser.getContent(dataSource.getInputStream());
    final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
    final String dataSourceName = getDataSourceName(part, dataSource);

    result.setName(dataSourceName);
    return result;
}

From source file:org.znerd.yaff.activation.XMLDataSource.java

/**
 * Constructs a new <code>XMLDataSource</code> from an existing
 * <code>DataSource</code> object.
 *
 * @param dataSource/*from   ww w .j av a2s.c  o  m*/
 *    the {@link DataSource}, cannot be <code>null</code>.
 *
 * @throws IllegalArgumentException
 *    if <code>dataSource == null</code>.
 *
 * @throws IOException
 *    if there was an I/O error while reading from the input stream of the
 *    data source.
 *
 * @throws ParseException
 *    if there was a parsing error while parsing the content as XML.
 */
public XMLDataSource(DataSource dataSource) throws IllegalArgumentException, IOException, ParseException {

    // Check preconditions
    MandatoryArgumentChecker.check("dataSource", dataSource);

    // The DataSource could be an XDataSource instance
    XDataSource xds = (dataSource instanceof XDataSource) ? (XDataSource) dataSource : null;

    // Populate fields
    _file = (xds != null) ? xds.getFile() : null;
    _name = dataSource.getName();
    _lastModified = (xds != null) ? xds.lastModified() : System.currentTimeMillis();
    _xml = new ElementParser().parse(dataSource.getInputStream());
}

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  ww .  j av  a 2  s  . c o m*/
 * 
 * @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.//from   www. j  av  a2  s.  com
 * 
 * @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.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message./*from  w  w  w.  j a  v a2  s  .  co 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);
    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);
    }
}