Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

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

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

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

private DataHandler convert(Field<?> key, Serializable value) throws IOException {
    if (value == null)
        return null;

    DataSource source = null;/*from   w ww  . ja  v a  2s  . c o  m*/
    if (key.getType().isAssignableFrom(File.class)) {
        source = new FileDataSource((File) value);
    } else {
        source = new JaxbSerializableDataSource(key.getName(), value);
    }
    return new DataHandler(source);
}

From source file:org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.openjpa.entity.AttachmentDAOImpl.java

@Override
public DataHandler getContent() {
    ByteArrayDataSource rawData = new ByteArrayDataSource(this.content);
    return new DataHandler(rawData);
}

From source file:org.openhealthtools.openxds.repository.relationaldb.RelationalDBRepositoryServiceImpl.java

@Transactional(propagation = Propagation.REQUIRES_NEW)
public XdsRepositoryItem getRepositoryItem(String documentUniqueId, RepositoryRequestContext context)
        throws RepositoryException {
    XdsRepositoryItemImpl repositoryItem = null;
    // Strip off the "urn:uuid:"
    String id = Utility.getInstance().stripId(documentUniqueId);
    try {//from  w  w w  .  j a  v  a 2s  .  co  m
        Repository repository = xdsRepositoryManagerDao.getXdsRepositoryBean(id);
        if (repository != null) {
            DataHandler contentDataHandler = new DataHandler(
                    new ByteArrayDataSource(repository.getBinaryContent(), repository.getMimeType()));
            repositoryItem = new XdsRepositoryItemImpl();
            repositoryItem.setDataHandler(contentDataHandler);
            repositoryItem.setDocumentUniqueId(repository.getDocumentUniqueId());
            repositoryItem.setMimeType(repository.getMimeType());
        }
    } catch (Exception e) {
        log.error(e);
        throw new RepositoryException(e);
    }
    return repositoryItem;

}

From source file:org.bimserver.unittests.TestClientEmfModelCheckin.java

@Test
public void test() {
    bimServerClient = new BimServerClient(bimServer.getPluginManager());
    try {/*  w w  w.ja v  a2  s  .  c  om*/
        UsernamePasswordAuthenticationInfo usernamePasswordAuthenticationInfo = new UsernamePasswordAuthenticationInfo(
                "admin@bimserver.org", "admin");
        bimServerClient.setAuthentication(usernamePasswordAuthenticationInfo);
        bimServerClient.connectProtocolBuffers("localhost", 8020);
    } catch (ConnectionException e1) {
        e1.printStackTrace();
    }
    try {
        long poid = createProject();

        File file = new File("../TestData/data/AC11-FZK-Haus-IFC.ifc");
        DataSource dataSource = new org.bimserver.utils.FileDataSource(file);
        DataHandler dataHandler = new DataHandler(dataSource);
        Integer checkin = bimServerClient.getServiceInterface().checkin(poid, "lala", "IfcStepDeserializer",
                file.length(), dataHandler, false, true);
        SCheckinResult checkinState = bimServerClient.getServiceInterface().getCheckinState(checkin);

        IfcModelInterface model = bimServerClient.getModel(checkinState.getRevisionId());
        IfcStepSerializer serializer = new IfcStepSerializer();
        serializer.init(model, null, bimServer.getPluginManager(), null);
        File output = new File("output");
        if (!output.exists()) {
            output.mkdir();
        }
        serializer.writeToFile(new File(output, "test.ifc"));
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.wso2.carbon.analytics.activitydashboard.ui.ActivityDashboardClient.java

public String[] searchActivities(long fromTime, long toTime, SearchExpressionTree searchExpressionTree)
        throws ActivityDashboardAdminServiceActivityDashboardExceptionException {
    try {//from  w w w.j a va 2 s .c  o  m
        ActivitySearchRequest searchRequest = new ActivitySearchRequest();
        searchRequest.setFromTime(fromTime);
        searchRequest.setToTime(toTime);
        searchRequest.setSearchTreeExpression(
                new DataHandler(new ByteArrayDataSource(serializeObject(searchExpressionTree))));
        return stub.getActivities(searchRequest);
    } catch (RemoteException e) {
        String message = "Error while getting the activities from time: " + fromTime + ", to time : " + toTime;
        logger.error(message, e);
        throw getActivityException(message, e);
    }
}

From source file:org.wso2.appserver.integration.tests.carbonappservice.WSAS1910CAppArtifactIdentificationTestCase.java

@Test(groups = "wso2.as", description = "Upload CApp which contains an axis2 service and check if setCAppArtifact is true")
public void verifyIndicatorAxis2ServiceCApp() throws Exception {
    URL urlAxisCApp = new URL(
            "file://" + FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "AS"
                    + File.separator + "car" + File.separator + axis2CApp + "-" + appVersion + ".car");
    DataHandler dataHandler = new DataHandler(urlAxisCApp);
    carbonAppClient.uploadCarbonAppArtifact(axis2CApp + "-" + appVersion + ".car", dataHandler);
    AxisServiceClientUtils.waitForServiceDeployment(asServer.getContextUrls().getServiceUrl() + "/Calculator");
    ServiceMetaData serviceMetaData = serviceAdminClient.getServicesData("Calculator");
    assertTrue(serviceMetaData.getCAppArtifact(), "The Axis2 Serice is not indicated as a CApp artifact.");
}

From source file:org.apache.axis2.transport.http.MultipartFormDataFormatterTest.java

public void testTransportHeadersOfFileAttachments() throws Exception {

    String FILE_NAME = "binaryFile.xml";
    String FIELD_NAME = "fileData";
    String CONTENT_TYPE_VALUE = "text/xml";
    String MEDIATE_ELEMENT = "mediate";
    String FILE_KEY = "fileAttachment";
    String CONTENT_DISPOSITION = "Content-Disposition";
    String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding";
    String CONTENT_TYPE = "Content-Type";
    String FORM_DATA_ELEMENT = "form-data";
    String NAME_ELEMENT = "name";
    String FILE_NAME_ELEMENT = "filename";
    String CONTENT_TRANSFER_ENCODING_VALUE = "binary";

    MultipartFormDataFormatter formatter = new MultipartFormDataFormatter();
    File binaryAttachment = getTestResourceFile(FILE_NAME);

    MessageContext mc = new MessageContext();

    DiskFileItem diskFileItem = null;/*from w ww.  ja  v a  2  s. c  o  m*/
    InputStream input = null;
    try {
        if (binaryAttachment.exists() && !binaryAttachment.isDirectory()) {
            diskFileItem = (DiskFileItem) new DiskFileItemFactory().createItem(FIELD_NAME, CONTENT_TYPE_VALUE,
                    true, binaryAttachment.getName());
            input = new FileInputStream(binaryAttachment);
            OutputStream os = diskFileItem.getOutputStream();
            int ret = input.read();
            while (ret != -1) {
                os.write(ret);
                ret = input.read();
            }
            os.flush();
        }

    } finally {
        input.close();
    }

    DataSource dataSource = new DiskFileDataSource(diskFileItem);
    DataHandler dataHandler = new DataHandler(dataSource);

    SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory();
    SOAPEnvelope soapEnvelope = soapFactory.getDefaultEnvelope();
    SOAPBody body = soapEnvelope.getBody();
    OMElement bodyFirstChild = soapFactory.createOMElement(new QName(MEDIATE_ELEMENT), body);
    OMText binaryNode = soapFactory.createOMText(dataHandler, true);
    soapFactory.createOMElement(FILE_KEY, null, bodyFirstChild).addChild(binaryNode);
    mc.setEnvelope(soapEnvelope);

    OMOutputFormat format = new OMOutputFormat();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    formatter.writeTo(mc, format, baos, true);

    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), format.getContentType()));
    BodyPart bp = mp.getBodyPart(0);
    String contentDispositionValue = FORM_DATA_ELEMENT + "; " + NAME_ELEMENT + "=\"" + FILE_KEY + "\"; "
            + FILE_NAME_ELEMENT + "=\"" + binaryAttachment.getName() + "\"";
    String contentTypeValue = bp.getHeader(CONTENT_TYPE)[0].split(";")[0];
    assertEquals(contentDispositionValue, bp.getHeader(CONTENT_DISPOSITION)[0]);
    assertEquals(CONTENT_TYPE_VALUE, contentTypeValue);
    assertEquals(CONTENT_TRANSFER_ENCODING_VALUE, bp.getHeader(CONTENT_TRANSFER_ENCODING)[0]);
}

From source file:es.pode.empaquetador.presentacion.agregar.local.AgregarLocalControllerImpl.java

/**
 * @see es.pode.empaquetador.presentacion.agregar.local.AgregarLocalController#agregar(org.apache.struts.action.ActionMapping, es.pode.empaquetador.presentacion.agregar.local.AgregarForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from w  w  w  .  j a va  2  s  .c o m*/
public final void agregar(ActionMapping mapping,
        es.pode.empaquetador.presentacion.agregar.local.AgregarForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    FormFile archivos = form.getArchivo();

    //convierto el FormFile en un DataHandler
    InternetHeaders ih = new InternetHeaders();
    MimeBodyPart mbp = null;
    DataSource source = null;
    DataHandler dFichero = null;
    mbp = new MimeBodyPart(ih, archivos.getFileData());
    source = new MimePartDataSource(mbp);
    dFichero = new DataHandler(source);
    FicheroVO fichero = new FicheroVO();
    fichero.setDatos(dFichero);
    fichero.setNombre(archivos.getFileName());
    fichero.setTipoMime(archivos.getContentType());

    ///////////////////////////

    EmpaquetadorSession sesEmpaq = this.getEmpaquetadorSession(request);
    List subman = sesEmpaq.getSubmanifestPath();

    String identificador = sesEmpaq.getIdLocalizador();

    List idCollection = sesEmpaq.getIdCollection();
    String identificadorUltimo = "";

    if (idCollection != null && idCollection.size() > 0) {
        Object ultimoIdCollection = idCollection.get(idCollection.size() - 1);

        if (idCollection.size() == 1) {

            OrganizacionVO organizacion = (OrganizacionVO) ultimoIdCollection;
            identificadorUltimo = organizacion.getIdentifier();
        } else if (idCollection.size() > 1) {
            GrupoVO grupo = (GrupoVO) ultimoIdCollection;
            identificadorUltimo = grupo.getIdentifier();
        }
    }
    String tipoEmpaquetador = sesEmpaq.getTipoEmpaquetador();
    try {
        if (tipoEmpaquetador.equals("Avanzado")) {
            if (subman.size() == 1) {
                this.getSrvGestorManifestService().agregarManifiestoZIP(identificador, dFichero, null);
            } else if (subman.size() > 1) {
                OdeVO ultimo = (OdeVO) subman.get(subman.size() - 1);
                String submanifestId = ultimo.getIdentifier();
                this.getSrvGestorManifestService().agregarManifiestoZIP(identificador, dFichero, submanifestId);
            }
        }

        else if (tipoEmpaquetador.equals("Basico")) {
            if (logger.isDebugEnabled())
                logger.debug("Estamos en el bsico");
            this.getSrvEmpaquetadorBasicoService().agregarLocal(identificador, fichero, identificadorUltimo);
        }
    } catch (Exception ex) {
        if (logger.isDebugEnabled())
            logger.error("Ocurrio un error al validar ODE " + identificador, ex);
        throw new ValidatorException("{portalempaquetado.avanzado.submanifiesto.error.agregarLocal}");
    }
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendFiles(String to, String subject, String text, Collection<File> attachments)
        throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    Transport t = session.getTransport("smtp");

    message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);/*from  w  ww .jav a  2s.  co m*/
    message.setSentDate(new Date());
    if (attachments == null || attachments.size() < 1) {
        message.setText(text);
    } else {
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(text);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (File attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);
    }

    t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

    t.sendMessage(message, message.getAllRecipients());
    t.close();
}

From source file:es.pode.administracion.presentacion.estructuraseducativas.tesauros.alta.AltaTesaurosControllerImpl.java

/**
 * @see es.pode.administracion.presentacion.estructuraseducativas.tesauros.alta.AltaTesaurosController#nuevoTesauro(org.apache.struts.action.ActionMapping, es.pode.administracion.presentacion.estructuraseducativas.tesauros.alta.NuevoTesauroForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*w  ww  . j  a v  a  2 s.  c  o m*/
public final void nuevoTesauro(ActionMapping mapping, NuevoTesauroForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    VdexVO[] resultado = null;
    List ficheros = this.getEstructurasSession(request).getVdexSubir();

    List arrayParam = new ArrayList();
    InternetHeaders ih = new InternetHeaders();
    MimeBodyPart mbp = null;
    DataSource source = null;
    DataHandler dh = null;
    for (int i = 0; i < ficheros.size(); i++) {
        try {
            FormFile ff = (FormFile) ficheros.get(i);
            mbp = new MimeBodyPart(ih, ff.getFileData());
            source = new MimePartDataSource(mbp);
            dh = new DataHandler(source);
            arrayParam.add(new ParamVdexVO(dh, ff.getFileName()));

        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("error al cargar la lista de paramVDEXVO");
            }
        }
    }
    try {
        SrvEstructurasEducativasService servicio = this.getSrvEstructurasEducativasService();
        resultado = servicio.subirTesauros((ParamVdexVO[]) arrayParam.toArray(new ParamVdexVO[0]));
        for (int i = 0; i < resultado.length; i++) {
            String[] nombreVdex = new String[1];
            nombreVdex[0] = ((FormFile) ficheros.get(i)).getFileName();
            if (resultado[i].getCodigoError() != null && !resultado[i].getCodigoError().equals("")) {
                logger.debug("hubo un error al crear la nueva taxonomia, se muestra el error en la jsp");
                this.saveErrorMessage(request, "estructuras.error.alta." + resultado[i].getCodigoError(),
                        nombreVdex);
            } else {
                this.saveSuccessMessage(request, "estructuras.tesauros.alta.exito", nombreVdex);

            }
        }

    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("error al dar de alta lista de tesauros");
        }
        this.saveErrorMessage(request, "estructuras.error.alta.0");
    }

}