Example usage for javax.activation DataHandler getInputStream

List of usage examples for javax.activation DataHandler getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Get the InputStream for this object.

Usage

From source file:org.apache.axis2.rpc.complex.ComplexDataTypesDocLitBareTest.java

/**
 * Auto generated test method/* ww w . ja v a  2 s . c  om*/
 */
public void testretByteArray() throws java.lang.Exception {

    byte[] input = new byte[] { (byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF };
    ComplexDataTypesDocLitBareStub.RetByteArray req = new ComplexDataTypesDocLitBareStub.RetByteArray();
    req.setInByteArray(new DataHandler(new ByteArrayDataSource(input)));
    DataHandler ret = stub.retByteArray(req).get_return();
    byte[] bytes = IOUtils.toByteArray(ret.getInputStream());
    assertTrue(Arrays.equals(bytes, input));
}

From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java

/**
 * Writes XML RepositoryItems as a RepositoryItemList. Ignores any other
 * type of RepositoryItem.s// ww  w .jav  a2 s . c  o  m
 */
void writeRepositoryItems(List<?> eos) throws IOException, RegistryException, ObjectNotFoundException {
    ServerRequestContext context = new ServerRequestContext("URLHandler.writeRepositoryItem", null);
    ServletOutputStream sout = response.getOutputStream();
    boolean doCommit = false;
    try {
        RepositoryItemListType ebRepositoryItemListType = bu.lcmFac.createRepositoryItemListType();

        Iterator<?> iter = eos.iterator();
        while (iter.hasNext()) {
            ExtrinsicObjectType eo = (ExtrinsicObjectType) iter.next();
            String id = eo.getId();

            RepositoryItem ri = QueryManagerFactory.getInstance().getQueryManager().getRepositoryItem(context,
                    id);

            if (ri == null) {
                throw new ObjectNotFoundException(id,
                        ServerResourceBundle.getInstance().getString("message.repositoryItem"));
            } else {
                if (eo.getMimeType().equals("text/xml")) {
                    DataHandler dataHandler = ri.getDataHandler();
                    InputStream fStream = dataHandler.getInputStream();

                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setNamespaceAware(true);
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document document = builder.parse(fStream);
                    Element rootElement = document.getDocumentElement();

                    ebRepositoryItemListType.getAny().add(rootElement);
                }
            }
        }
        // javax.xml.bind.Marshaller marshaller =
        // bu.lcmFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        JAXBElement<RepositoryItemListType> ebRepositoryItemList = bu.lcmFac
                .createRepositoryItemList(ebRepositoryItemListType);
        marshaller.marshal(ebRepositoryItemList, sout);
        doCommit = true;

    } catch (JAXBException e) {
        throw new RegistryException(e);
    } catch (ParserConfigurationException e) {
        throw new RegistryException(e);
    } catch (SAXException e) {
        throw new RegistryException(e);
    } finally {
        if (sout != null) {
            sout.close();
            sout = null;
        }
        try {
            closeContext(context, doCommit);
        } catch (Exception ex) {
            log.error(ex, ex);
        }
    }
}

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

@Test
public void testDecryptMessages() throws Exception {
    // STS//from w w w. j a va 2 s  . com
    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());
    String encryptionAlias = aliasesEnum.nextElement();
    X509Certificate encryptionCertificate = (X509Certificate) eHealthKeyStore.getCertificate(encryptionAlias);
    PrivateKey encryptionPrivateKey = (PrivateKey) eHealthKeyStore.getKey(encryptionAlias,
            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);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        GetFullMessageResponseType getFullMessageResponse = eHealthBoxClient.getMessage(messageId);
        DataHandler dataHandler = getFullMessageResponse.getMessage().getContentContext().getContent()
                .getDocument().getEncryptableBinaryContent();
        byte[] data;
        if (null != dataHandler) {
            data = IOUtils.toByteArray(dataHandler.getInputStream());
        } else {
            data = getFullMessageResponse.getMessage().getContentContext().getContent().getDocument()
                    .getEncryptableTextContent();
        }
        LOG.debug("data size: " + data.length);
        Unsealer unsealer = new Unsealer(encryptionPrivateKey, encryptionCertificate);
        unsealer.unseal(data);
    }
}

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

@Test
public void testGetMessageWithAttachments() throws Exception {
    // STS//  w w  w.j  av  a 2s.  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:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java

void writeRepositoryItem(ExtrinsicObjectType eo)
        throws IOException, RegistryException, ObjectNotFoundException {
    String id = eo.getId();//from www.j  ava2  s  .  c o m
    ServerRequestContext context = new ServerRequestContext("URLHandler.writeRepositoryItem", null);

    try {
        RepositoryItem ri = QueryManagerFactory.getInstance().getQueryManager().getRepositoryItem(context, id);

        if (ri == null) {
            throw new ObjectNotFoundException(id,
                    ServerResourceBundle.getInstance().getString("message.repositoryItem"));
        } else {
            response.setContentType(eo.getMimeType());

            DataHandler dataHandler = ri.getDataHandler();
            ServletOutputStream sout = response.getOutputStream();
            InputStream fStream = dataHandler.getInputStream();
            int bytesSize = fStream.available();
            byte[] b = new byte[bytesSize];
            fStream.read(b);
            sout.write(b);
            sout.close();
        }
        context.commit();
        context = null;
    } finally {
        if (context != null) {
            context.rollback();
        }

    }
}

From source file:org.taverna.server.master.TavernaServerSupport.java

public void copyDataToFile(DataHandler handler, File file) throws FilesystemAccessException {
    try {//from www. j av a  2  s . c  o  m
        copyStreamToFile(handler.getInputStream(), file);
    } catch (IOException e) {
        throw new FilesystemAccessException("problem constructing stream from data source", e);
    }
}

From source file:org.apache.abdera.util.AbstractStreamWriter.java

public StreamWriter writeElementText(DataHandler value) throws IOException {
    writeElementText(value.getInputStream());
    return this;
}

From source file:es.pode.modificador.presentacion.pendientes.ModificacionesPendientesControllerImpl.java

public void exportarTarea(ActionMapping mapping, ExportarTareaForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final int BUFFER_SIZE = 2048;
    Long idModificacion = form.getIdModificacion();
    ModificacionVO mod = this.getSrvHerramientaModificacion().obtenerModificacion(idModificacion);
    String nombre = mod.getNombre();
    ConfiguracionTarea tarea = this.getSrvHerramientaModificacion().obtenerConfiguracionTarea(idModificacion);
    DataHandler data;
    try {//  www  . j  a  v a 2s  .c  o  m
        data = this.getSrvHerramientaModificacion().exportarModificacion(tarea);
    } catch (Exception e) {
        logger.debug("Error al exportar modificacion: " + e);
        throw new ValidatorException("{exportarModificacion.error}");
    }

    response.setContentType("text/xml");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + nombre.replace(' ', '_').trim() + ".xml");
    OutputStream out = response.getOutputStream();
    InputStream in = data.getInputStream();
    logger.debug("Descargando fichero Configuracion.xml");
    byte[] buffer = new byte[BUFFER_SIZE];
    int count;
    while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
        out.write(buffer, 0, count);
    }

    out.flush();
}

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

public void testStoreMarshalledCommand() throws IOException, ParseException {
    // Create the ZIP file
    final File outFile = File.createTempFile("command", ".zip");
    outFile.deleteOnExit();//  ww  w.  j av a2  s  . co  m
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(outFile));

    // creating a test command
    final ICommand cmd = this.createTestCommand();

    // marshal command
    final ZipEntry commandEntry = new ZipEntry("command.xml");
    commandEntry.setComment("command.xml");
    zipOut.putNextEntry(commandEntry);

    final TeeOutputStream out = new TeeOutputStream(System.out, zipOut);
    final Map<String, DataHandler> attachments = this.docFactory.marshal(cmd, out);
    zipOut.closeEntry();

    // write attachments
    if (attachments != null) {
        for (Entry<String, DataHandler> attachment : attachments.entrySet()) {
            final String cid = attachment.getKey();
            final DataHandler data = attachment.getValue();

            final ZipEntry zipEntry = new ZipEntry(cid);
            zipEntry.setComment(data.getName());
            zipOut.putNextEntry(zipEntry);

            IOUtils.copy(data.getInputStream(), zipOut);
            zipOut.closeEntry();
        }
    }
    zipOut.close();
    System.out.println("Command written into file: " + outFile.toString());

    // print content
    final ZipFile zf = new ZipFile(outFile);
    for (Enumeration<? extends ZipEntry> entries = zf.entries(); entries.hasMoreElements();) {
        ZipEntry entry = entries.nextElement();
        System.out.println(entry.getName() + ": " + entry.getComment());
    }
    zf.close();
}

From source file:es.pode.administracion.presentacion.estructuraseducativas.taxonomias.listar.ListarTaxonomiasControllerImpl.java

public void exportar(ActionMapping mapping, ExportarForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final int BUFFER_SIZE = 2048;
    if (form.getNombre() != null && !form.getNombre().equals("") && form.getTipo() != null
            && !form.getTipo().equals("")) {
        DataHandler dh = null;

        try {//  w  w  w  .j a  v  a 2s  .  co  m
            if (form.getTipo().equals("TAX"))
                dh = this.getSrvEstructurasEducativasService().exportarVdex(form.getNombre(),
                        TipoVdex.TAXONOMIA);
            else
                dh = this.getSrvEstructurasEducativasService().exportarVdex(form.getNombre(),
                        TipoVdex.TESAUROS_BACK);
            if (dh != null) {
                response.setContentType("text/xml;charset=utf-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + form.getNombre());
                OutputStream out = response.getOutputStream();
                InputStream in = dh.getInputStream();
                logger.debug("Descargando metadata.xml");
                byte[] buffer = new byte[BUFFER_SIZE];
                int count;
                while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    out.write(buffer, 0, count);
                }
                out.flush();
            }

        } catch (Exception e) {
            logger.debug("error en la llamada al servicio estructuras educativas " + e.getMessage());
        }

    } else {
        logger.debug("error al intentar exportar el tesauros o taxonomias ");
    }

}