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:de.betterform.connector.serializer.MultipartRelatedSerializer.java

protected void visitNode(Map cache, Node node, MimeMultipart multipart) throws Exception {

    ModelItem item = (ModelItem) node.getUserData("");
    if (item != null && item.getDeclarationView().getDatatype() != null
            && item.getDeclarationView().getDatatype().equalsIgnoreCase("anyURI")) {
        String name = item.getFilename();
        if (name == null || item.getValue() == null || item.getValue().equals("")) {
            return;
        }//from   w  ww. j a v  a  2 s .  c o  m

        String cid = (String) cache.get(name);
        if (cid == null) {
            int count = multipart.getCount();
            cid = name + "@part" + (count + 1);

            MimeBodyPart part = new MimeBodyPart();
            part.setContentID("<" + cid + ">");

            DataHandler dh = new DataHandler(new ModelItemDataSource(item));
            part.setDataHandler(dh);

            part.addHeader("Content-Type", item.getMediatype());
            part.addHeader("Content-Transfer-Encoding", "base64");
            part.setDisposition("attachment");
            part.setFileName(name);
            multipart.addBodyPart(part);
            cache.put(name, cid);
        }

        Element element = (Element) node;
        // remove text node
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() != Node.TEXT_NODE) {
                continue;
            }
            n.setNodeValue("cid:" + cid);
            break;
        }
    } else {
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                visitNode(cache, n, multipart);
            }
        }
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassed(String adresaSephora, String from, String grupTestContent,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }/* w w w  .  jav a2s .c  o m*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(grupTestContent));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);
        //  System.out.println("message sent successfully");
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:org.apache.servicemix.camel.nmr.AttachmentTest.java

public void testAttachment() throws Exception {
    TestMtom mtomPort = createPort(MTOM_SERVICE, MTOM_PORT, TestMtom.class, true);
    try {//from   ww w .  j  av a  2s .c  om

        Holder<DataHandler> param = new Holder<DataHandler>();

        param.value = new DataHandler(new ByteArrayDataSource("foobar".getBytes(), "application/octet-stream"));

        Holder<String> name = new Holder<String>("call detail");
        mtomPort.testXop(name, param);
        assertEquals("call detailfoobar", name.value);
        assertNotNull(param.value);
        InputStream bis = param.value.getDataSource().getInputStream();
        byte b[] = new byte[10];
        bis.read(b, 0, 10);
        String attachContent = new String(b);
        assertEquals(attachContent, "testfoobar");
    } catch (UndeclaredThrowableException ex) {
        throw (Exception) ex.getCause();
    }

}

From source file:org.wso2.appserver.integration.tests.carbontools.CleanRegistryCommandTestCase.java

@Test(groups = "wso2.as", description = "Add resource and test --cleanRegistry startup argument")
public void testCleanResource() throws Exception {
    boolean isResourceFound;

    String resourcePath = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "AS"
            + File.separator + "carbontools" + File.separator + "resource.txt";

    DataHandler dh = new DataHandler(new URL("file:///" + resourcePath));
    resourceAdminServiceClient.addResource(configRegistryRepoPath + "resource.txt", "txt", "testDesc", dh);
    isResourceFound = true;//from   w w w . ja v a  2 s  . co  m
    CarbonTestServerManager.stop();
    try {
        // start with -Dsetup command
        serverPropertyMap.put("--cleanRegistry", "");

        CarbonTestServerManager.start(serverPropertyMap);

        boolean startupStatus = CarbonCommandToolsUtil.isServerStartedUp(context, portOffset);
        log.info("Server startup status : " + startupStatus);
        initEnvironment();
        resourceAdminServiceClient = new ResourceAdminServiceClient(backendURLForInstance002,
                sessionCookieForInstance002);
        resourceAdminServiceClient.getResource(configRegistryRepoPath + "resource.txt");
    } catch (Exception ex) {
        if (ex.getMessage().contains("Resource does not exist")) {
            isResourceFound = false;
        }
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    assertFalse(isResourceFound, "Resource not deleted successfully");
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private void sendMessage(final String content) {
    try {//from w w  w . j  a v  a 2  s  .  c  om
        MimeMessage msg = new MimeMessage(sessionProvider.get());
        msg.setSubject("jFunk E-mail Report");
        msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get());

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=UTF-8");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif")));
        messageBodyPart.setHeader("Content-ID", "<check>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif")));
        messageBodyPart.setHeader("Content-ID", "<error>");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        smtpClientProvider.get().send(msg);

        int anzahlRecipients = msg.getAllRecipients().length;
        log.info(
                "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get());
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    } catch (MailException e) {
        log.error("Error while sending report e-mail", e);
    }
}

From source file:com.nortal.jroad.example.endpoints.AttachmentEchoEndpoint.java

@Override
protected AttachmentEchoResponse invokeBean(AttachmentEchoRequest requestBean) throws IOException {
    // Creation of a response object -- must correspond to
    // response type defined in XML Schema definition.
    AttachmentEchoResponse response = new AttachmentEchoResponse();

    // Create a temporary object to store our data
    byte[] data = null;

    // Logging/*w  w w  .j  a v  a  2s .c  o  m*/
    log.info("Received attachment, type: " + requestBean.getNest().getAttachment().getContentType() + ", size: "
            + requestBean.getNest().getAttachment().getInputStream().available());
    // Using a Spring helper class we read an InputStream to a byte array.
    // In real situations you probably want to pass the InputStream around.
    data = FileCopyUtils.copyToByteArray(requestBean.getNest().getAttachment().getInputStream());

    /*
     * JAXB generates DataHandler type setters for attachments, so you need to find a way to get your data into a
     * DataHandler. The easiest way to accomplish this, is to create a DataSource. A DataSource used here only needs to
     * provide an InputStream and a content type. A simple DataSource, which takes a byte array and content-type in
     * string form is included. Usually you would use something like FileDataSource, UrlDataSource or you can easily
     * implement your own. All a DataSource basically does in this context is give an InputStream and a content type for
     * that InputStream. An alternative way is to define a DataContentHandler and pass an object+content type when
     * creating a DataHandler. This way you will have to implement a DataContentHandler and DataContentHandlerFactory,
     * however.
     */
    DataSource ds = new ByteArrayDataSource(requestBean.getNest().getAttachment().getContentType(), data);

    // Now we can easily construct a DataHandler and pass it to JAXB.
    // Converting it to an attachment is handled by the library.
    DataHandler dh = new DataHandler(ds);
    AttachmentEchoNest nest = new AttachmentEchoNest();
    nest.setAttachment(dh);
    response.setNest(nest);

    // Finally, we return the response object.
    return response;
}

From source file:it.cnr.icar.eric.client.xml.registry.infomodel.ExtrinsicObjectImpl.java

public ExtrinsicObjectImpl(LifeCycleManagerImpl lcm, ExtrinsicObjectType ebExtrinsicObj) throws JAXRException {
    super(lcm, ebExtrinsicObj);

    mimeType = ebExtrinsicObj.getMimeType();
    opaque = ebExtrinsicObj.isIsOpaque();
    contentVersionInfo = ebExtrinsicObj.getContentVersionInfo();

    try {/*from w ww.  ja  v  a2s.  c o m*/
        HashMap<String, Serializable> slotsMap = BindingUtility.getInstance()
                .getSlotsFromRegistryObject(ebExtrinsicObj);
        @SuppressWarnings("static-access")
        String slotName = BindingUtility.getInstance().CANONICAL_SLOT_EXTRINSIC_OBJECT_REPOSITORYITEM_URL;
        if (slotsMap.containsKey(slotName)) {
            String riURLStr = (String) slotsMap.get(slotName);
            File riFile = new File(riURLStr);
            repositoryItem = new DataHandler(new FileDataSource(riFile));

            //Remove transient slot
            this.removeSlot(slotName);
        }
    } catch (JAXBException e) {
        throw new JAXRException(e);
    }
}

From source file:com.clustercontrol.ws.cloud.CloudCommonEndpoint.java

/**
 * [Template] ?//from   w  ww  .j a  v  a  2 s. c o m
 * 
 * HinemosAgentAccess???
 * 
 * @throws HinemosUnknown
 * @throws InvalidRole
 * @throws InvalidUserPass
 */
@XmlMimeType("application/octet-stream")
public DataHandler downloadScripts(String filename) throws InvalidUserPass, InvalidRole, HinemosUnknown {
    ArrayList<SystemPrivilegeInfo> systemPrivilegeList = new ArrayList<SystemPrivilegeInfo>();
    systemPrivilegeList
            .add(new SystemPrivilegeInfo(FunctionConstant.CLOUDMANAGEMENT, SystemPrivilegeMode.READ));
    HttpAuthenticator.authCheck(wsctx, systemPrivilegeList);

    String homeDir = System.getProperty("hinemos.manager.home.dir");
    String filepath = homeDir + "/var/cloud/" + filename;
    File file = new File(filepath);
    if (!file.exists()) {
        m_log.error("file not found : " + filepath);
        return null;
    }
    FileDataSource source = new FileDataSource(file);
    DataHandler dataHandler = new DataHandler(source);
    return dataHandler;
}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {// w w w  .  ja  v  a2  s .  c o m
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:es.pode.administracion.presentacion.estructuraseducativas.taxonomias.alta.AltaTaxonomiasControllerImpl.java

public final void nuevaTaxonomia(ActionMapping mapping, NuevaTaxonomiaForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    VdexVO[] resultado = null;//from  w w w  .j  a v a 2 s . co  m

    List ficheros = new ArrayList();
    if (form.getFichero1() != null && form.getFichero1().getFileName() != null
            && !form.getFichero1().getFileName().equals("")) //&& form.getFichero1().getFileSize()>0 
        ficheros.add(form.getFichero1());
    if (form.getFichero2() != null && form.getFichero2().getFileName() != null
            && !form.getFichero2().getFileName().equals(""))
        ficheros.add(form.getFichero2());
    if (form.getFichero3() != null && form.getFichero3().getFileName() != null
            && !form.getFichero3().getFileName().equals(""))
        ficheros.add(form.getFichero3());
    if (form.getFichero4() != null && form.getFichero4().getFileName() != null
            && !form.getFichero4().getFileName().equals(""))
        ficheros.add(form.getFichero4());
    if (form.getFichero5() != null && form.getFichero5().getFileName() != null
            && !form.getFichero5().getFileName().equals(""))
        ficheros.add(form.getFichero5());

    if (ficheros.size() == 0) {
        throw new ValidatorException("{estructuras.taxonomias.error.fichero.vacio}");
    }

    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.subirBackups((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.taxonomias.alta.exito", nombreVdex);
            }
        }

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

}