Example usage for javax.mail.internet MimePartDataSource MimePartDataSource

List of usage examples for javax.mail.internet MimePartDataSource MimePartDataSource

Introduction

In this page you can find the example usage for javax.mail.internet MimePartDataSource MimePartDataSource.

Prototype

public MimePartDataSource(MimePart part) 

Source Link

Document

Constructor, that constructs a DataSource from a MimePart.

Usage

From source file:com.zimbra.cs.service.mail.CreateContact.java

private static Attachment parseAttachment(Element elt, String name, ZimbraSoapContext zsc,
        OperationContext octxt, Contact existing) throws ServiceException {
    // check for uploaded attachment
    String attachId = elt.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
    if (attachId != null) {
        if (Contact.isSMIMECertField(name)) {
            elt.setText(parseCertificate(elt, name, zsc, octxt, existing));
            return null;
        } else {/*from ww  w  .  ja v  a2 s.c om*/
            Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), attachId,
                    zsc.getAuthToken());
            UploadDataSource uds = new UploadDataSource(up);
            return new Attachment(new DataHandler(uds), name, (int) up.getSize());
        }
    }

    int itemId = (int) elt.getAttributeLong(MailConstants.A_ID, -1);
    String part = elt.getAttribute(MailConstants.A_PART, null);
    if (itemId != -1 || (part != null && existing != null)) {
        MailItem item = itemId == -1 ? existing
                : getRequestedMailbox(zsc).getItemById(octxt, itemId, MailItem.Type.UNKNOWN);

        try {
            if (item instanceof Contact) {
                Contact contact = (Contact) item;
                if (part != null && !part.equals("")) {
                    try {
                        int partNum = Integer.parseInt(part) - 1;
                        if (partNum >= 0 && partNum < contact.getAttachments().size()) {
                            Attachment att = contact.getAttachments().get(partNum);
                            return new Attachment(att.getDataHandler(), name, att.getSize());
                        }
                    } catch (NumberFormatException nfe) {
                    }
                    throw ServiceException.INVALID_REQUEST("invalid contact part number: " + part, null);
                } else {
                    VCard vcf = VCard.formatContact(contact);
                    return new Attachment(vcf.getFormatted().getBytes("utf-8"), "text/x-vcard; charset=utf-8",
                            name, vcf.fn + ".vcf");
                }
            } else if (item instanceof Message) {
                Message msg = (Message) item;
                if (part != null && !part.equals("")) {
                    try {
                        MimePart mp = Mime.getMimePart(msg.getMimeMessage(), part);
                        if (mp == null) {
                            throw MailServiceException.NO_SUCH_PART(part);
                        }
                        DataSource ds = new MimePartDataSource(mp);
                        return new Attachment(new DataHandler(ds), name);
                    } catch (MessagingException me) {
                        throw ServiceException.FAILURE("error parsing blob", me);
                    }
                } else {
                    DataSource ds = new MessageDataSource(msg);
                    return new Attachment(new DataHandler(ds), name, (int) msg.getSize());
                }
            } else if (item instanceof Document) {
                Document doc = (Document) item;
                if (part != null && !part.equals("")) {
                    throw MailServiceException.NO_SUCH_PART(part);
                }
                DataSource ds = new DocumentDataSource(doc);
                return new Attachment(new DataHandler(ds), name, (int) doc.getSize());
            }
        } catch (IOException ioe) {
            throw ServiceException.FAILURE("error attaching existing item data", ioe);
        } catch (MessagingException e) {
            throw ServiceException.FAILURE("error attaching existing item data", e);
        }
    }

    return null;
}

From source file:es.pode.administracion.presentacion.noticias.crear.CrearControllerImpl.java

public String tratamientoImagen(FormFile imagenFile) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Realizamos el tratamiento de la imagen [" + imagenFile + "]");
    ImagenVO imagen = new ImagenVO();
    InternetHeaders ih = new InternetHeaders();
    MimeBodyPart mbp = new MimeBodyPart(ih, imagenFile.getFileData());

    DataSource source = new MimePartDataSource(mbp);
    DataHandler dImagen = new DataHandler(source);

    imagen.setDatos(dImagen);/*from w w  w. java 2  s . c o m*/
    imagen.setNombre(imagenFile.getFileName());
    imagen.setMimeType(imagenFile.getContentType());
    String sUrlImagen = this.getSrvNoticiasService().almacenarImagenNoticia(imagen);
    return sUrlImagen;
}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasico.CatBasicoControllerImpl.java

public String submitImportar(ActionMapping mapping, SubmitImportarForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String accion = form.getAccion();
    String resAction = "";
    ResourceBundle datosResources = I18n.getInstance().getResource("application-resources",
            (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE));
    if (datosResources.getString("catalogadorBasico.importar.aceptar").equals(accion)) {
        resAction = "Aceptar";

        if (form.getFichero() == null || form.getFichero().getFileName().equals(""))
            throw new ValidatorException("{catalogadorBasico.importar.error.ficherovacio}");

        //crear el datahandler
        InternetHeaders ih = new InternetHeaders();
        MimeBodyPart mbp = null;//from w ww  .ja  v a2 s  .co  m
        DataSource source = null;
        DataHandler dh = null;
        try {
            FormFile ff = (FormFile) form.getFichero();
            mbp = new MimeBodyPart(ih, ff.getFileData());
            source = new MimePartDataSource(mbp);
            dh = new DataHandler(source);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("error al crear el datahandler");
            }
            throw new ValidatorException("{catalogadorBasico.importar.error}");
        }

        //validar el fichero
        Boolean valido = new Boolean(false);
        try {
            valido = this.getSrvValidadorService().obtenerValidacionLomes(dh);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("error al llamar al servicio de validacin");
            }
            throw new ValidatorException("{catalogadorBasico.importar.error.novalido}");
        }

        if (!valido.booleanValue())
            throw new ValidatorException("{catalogadorBasico.importar.error.novalido}");

        //agregar el datahandler a sesion
        this.getCatalogadorBSession(request).setLomesImportado(dh);

    } else if (datosResources.getString("catalogadorBasico.importar.cancelar").equals(accion)) {
        resAction = "Cancelar";
    }

    return resAction;

}

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

public String addMtomAttachment(byte[] data, int offset, int length, String mimeType, String namespace,
        String localPart) {/* w  ww.  ja v  a 2s  .  c o m*/

    if (offset != 0 || length != data.length) {
        int len = length - offset;
        byte[] newData = new byte[len];
        System.arraycopy(data, offset, newData, 0, len);
        data = newData;
    }

    if (mimeType == null || mimeType.length() == 0) {
        mimeType = APPLICATION_OCTET;
    }

    if (log.isDebugEnabled()) {
        log.debug("Adding MTOM/XOP byte array attachment for element: " + "{" + namespace + "}" + localPart);
    }

    String cid = null;

    try {
        // Create MIME Body Part
        final InternetHeaders ih = new InternetHeaders();
        final byte[] dataArray = data;
        ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeType);
        final MimeBodyPart mbp = (MimeBodyPart) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                try {
                    return new MimeBodyPart(ih, dataArray);
                } catch (MessagingException e) {
                    throw new OMException(e);
                }
            }
        });

        //Create a data source for the MIME Body Part
        MimePartDataSource mpds = (MimePartDataSource) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return new MimePartDataSource(mbp);
            }
        });
        long dataLength = data.length;
        Integer value = null;
        if (msgContext != null) {
            value = (Integer) msgContext.getProperty(Constants.Configuration.MTOM_THRESHOLD);
        } else if (log.isDebugEnabled()) {
            log.debug(
                    "The msgContext is null so the MTOM threshold value can not be determined; it will default to 0.");
        }

        int optimizedThreshold = (value != null) ? value.intValue() : 0;

        if (optimizedThreshold == 0 || dataLength > optimizedThreshold) {
            DataHandler dataHandler = new DataHandler(mpds);
            cid = addDataHandler(dataHandler, false);
        }

        // Add the content id to the mime body part
        mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid);
    } catch (MessagingException e) {
        throw new OMException(e);
    }

    return cid == null ? null : "cid:" + cid;
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.Attachment.java

private static DataHandler createDataHandler(Object value, Class cls, String[] mimeTypes, String cid) {
    if (log.isDebugEnabled()) {
        System.out.println("Construct data handler for " + cls + " cid=" + cid);
    }/*from w  w  w. j  av  a  2  s  .c o m*/
    DataHandler dh = null;
    if (cls.isAssignableFrom(DataHandler.class)) {
        dh = (DataHandler) value;
        if (dh == null) {
            return dh; //return if DataHandler is null
        }

        try {
            Object content = dh.getContent();
            // If the content is a Source, convert to a String due to 
            // problems with the DataContentHandler
            if (content instanceof Source) {
                if (log.isDebugEnabled()) {
                    System.out
                            .println("Converting DataHandler Source content to " + "DataHandlerString content");
                }
                byte[] bytes = (byte[]) ConvertUtils.convert(content, byte[].class);
                String newContent = new String(bytes);
                return new DataHandler(newContent, mimeTypes[0]);
            }
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    } else {
        try {
            byte[] bytes = createBytes(value, cls, mimeTypes);
            // Create MIME Body Part
            InternetHeaders ih = new InternetHeaders();
            ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeTypes[0]);
            MimeBodyPart mbp = new MimeBodyPart(ih, bytes);

            //Create a data source for the MIME Body Part
            MimePartDataSource ds = new MimePartDataSource(mbp);

            dh = new DataHandler(ds);
            mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid);
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }
    return dh;
}