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:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java

@Override
public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) {
    return new AbstractMailSendBuilder() {
        @Override//from w  w  w .j  ava 2s . c  om
        public void send(final String content) throws Exception {
            __sendExecPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed());
                        //
                        for (String _to : getTo()) {
                            _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));
                        }
                        for (String _cc : getCc()) {
                            _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc));
                        }
                        for (String _bcc : getBcc()) {
                            _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc));
                        }
                        //
                        if (getLevel() != null) {
                            switch (getLevel()) {
                            case LEVEL_HIGH:
                                _message.setHeader("X-MSMail-Priority", "High");
                                _message.setHeader("X-Priority", "1");
                                break;
                            case LEVEL_NORMAL:
                                _message.setHeader("X-MSMail-Priority", "Normal");
                                _message.setHeader("X-Priority", "3");
                                break;
                            case LEVEL_LOW:
                                _message.setHeader("X-MSMail-Priority", "Low");
                                _message.setHeader("X-Priority", "5");
                                break;
                            default:
                            }
                        }
                        //
                        String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8");
                        _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(),
                                serverCfgMeta.getDisplayName(), _charset));
                        _message.setSubject(getSubject(), _charset);
                        // 
                        Multipart _container = new MimeMultipart();
                        // 
                        MimeBodyPart _textBodyPart = new MimeBodyPart();
                        if (getMimeType() == null) {
                            mimeType(IMailSender.MimeType.TEXT_PLAIN);
                        }
                        _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset);
                        _container.addBodyPart(_textBodyPart);
                        // ??<img src="cid:<CID_NAME>">
                        for (PairObject<String, File> _file : getAttachments()) {
                            if (_file.getValue() != null) {
                                MimeBodyPart _fileBodyPart = new MimeBodyPart();
                                FileDataSource _fileDS = new FileDataSource(_file.getValue());
                                _fileBodyPart.setDataHandler(new DataHandler(_fileDS));
                                if (_file.getKey() != null) {
                                    _fileBodyPart.setHeader("Content-ID", _file.getKey());
                                }
                                _fileBodyPart.setFileName(_fileDS.getName());
                                _container.addBodyPart(_fileBodyPart);
                            }
                        }
                        // ??
                        _message.setContent(_container);
                        Transport.send(_message);
                    } catch (Exception e) {
                        throw new RuntimeException(RuntimeUtils.unwrapThrow(e));
                    }
                }
            });
        }
    };
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLFilteringService.java

@SuppressWarnings("unchecked")
public ServiceOutput invoke(ServerRequestContext context, ServiceInput si, ServiceType service,
        InvocationController invocationController, UserType user) throws RegistryException {
    if (log.isTraceEnabled()) {
        log.trace("CanonicalXMLFilteringService.invoke()");
    }//from   w  w  w  .  j  av a 2 s  .  com
    ServiceOutput so = new ServiceOutput();
    so.setOutput(context);
    RepositoryItem repositoryItem = si.getRepositoryItem();

    String roId = si.getRegistryObject().getId();

    ServerRequestContext outputContext = context; //new RequestContext(null);

    try {

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("subjectId", context.getUser().getId());

        //First filter the RegistryObject metadata
        StreamSource input = getAsStreamSource(si.getRegistryObject());
        StreamSource xslt = rm.getAsStreamSource(invocationController.getEoId());

        //Specify empty value to indicate that only metadata should be transformed
        //in this first XSLT invocation.
        params.put("repositoryItem", "");
        File output = runXSLT(input, xslt, getURIResolver(context), params);

        JAXBElement<RegistryObjectType> ebRegistryObject = (JAXBElement<RegistryObjectType>) bu.getJAXBContext()
                .createUnmarshaller().unmarshal(output);

        // take ComplexType from Element
        RegistryObjectType ebRegistryObjectType = ebRegistryObject.getValue();

        //Replace input RegistryObject with output RegistryObject.
        outputContext.getQueryResults().remove(si.getRegistryObject());
        outputContext.getQueryResults().add(ebRegistryObjectType);

        //Now filter the RepositoryItem content if any
        if (repositoryItem != null) {
            input = new StreamSource(repositoryItem.getDataHandler().getInputStream());
            xslt = rm.getAsStreamSource(invocationController.getEoId());

            params.put("repositoryItem", roId);
            output = runXSLT(input, xslt, getURIResolver(context), params);

            RepositoryItem outputRI = new RepositoryItemImpl(roId, new DataHandler(new FileDataSource(output)));

            //Replace input RepositoryItem with output RepositoryItem.
            outputContext.getRepositoryItemsMap().put(roId, outputRI);
        }

        // TODO: User should refer to "Service object for the
        // Content Management Service that generated the
        // Cataloged Content."
        outputContext.setUser(user);

    } catch (Exception e) {
        if (outputContext != context) {
            outputContext.rollback();
        }
        throw new RegistryException(e);
    }

    so.setOutput(outputContext);

    // Setting this error list is redundant, but Content Validation Services
    // currently output a Boolean and a RegistryErrorList, so using
    // same mechanism to report errors from Content Filtering Services.
    so.setErrorList(outputContext.getErrorList());

    if (outputContext != context) {
        outputContext.commit();
    }

    return so;
}

From source file:org.wso2.appserver.integration.resources.resource.test.SymlinkTestCase.java

@Test(groups = { "wso2.as" })
public void testAddArtifacts()
        throws ResourceAdminServiceExceptionException, IOException, XPathExpressionException {
    CollectionContentBean collectionContentBean = resourceAdminServiceClient.getCollectionContent("/");
    if (collectionContentBean.getChildCount() > 0) {
        String[] childPath = collectionContentBean.getChildPaths();
        for (int i = 0; i <= childPath.length - 1; i++) {
            if (childPath[i].equalsIgnoreCase(PARENT_PATH)) {
                resourceAdminServiceClient.deleteResource(PARENT_PATH);
            }/* w  w  w . j ava2  s  .c  o  m*/
        }
    }
    String collectionPath = resourceAdminServiceClient.addCollection("/", "TestAutomation", "", "");
    String authorUserName = resourceAdminServiceClient.getResource(PARENT_PATH)[0].getAuthorUserName();
    assertTrue(asServer.getContextTenant().getContextUser().getUserName().equalsIgnoreCase(authorUserName),
            PARENT_PATH + " creation failure");
    log.info("collection added to " + collectionPath);

    collectionPath = resourceAdminServiceClient.addCollection(PARENT_PATH, SYMLINK_PARENT_COLL_NAME, "", "");
    authorUserName = resourceAdminServiceClient.getResource(PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME)[0]
            .getAuthorUserName();
    assertTrue(asServer.getContextTenant().getContextUser().getUserName().equalsIgnoreCase(authorUserName),
            PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME + " creation failure");
    log.info("collection added to " + collectionPath);

    collectionPath = resourceAdminServiceClient.addCollection(PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME,
            TEST_COLLECTION1, "", "");
    authorUserName = resourceAdminServiceClient
            .getResource(PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME + "/" + TEST_COLLECTION1)[0]
                    .getAuthorUserName();
    assertTrue(asServer.getContextTenant().getContextUser().getUserName().equalsIgnoreCase(authorUserName),
            PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME + "/" + TEST_COLLECTION1 + " creation failure");
    log.info("collection added to " + collectionPath);

    collectionPath = resourceAdminServiceClient.addCollection(PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME,
            TEST_COLLECTION2, "", "");
    authorUserName = resourceAdminServiceClient
            .getResource(PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME + "/" + TEST_COLLECTION2)[0]
                    .getAuthorUserName();
    assertTrue(asServer.getContextTenant().getContextUser().getUserName().equalsIgnoreCase(authorUserName),
            PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME + "/" + TEST_COLLECTION2 + " creation failure");

    log.info("collection added to " + collectionPath);

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

    DataHandler dh = new DataHandler(new URL("file:///" + resource));

    resourceAdminServiceClient.addResource(
            PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME + "/" + TEST_COLLECTION1 + "/" + RESOURCE_NAME,
            "text/html", "txtDesc", dh);

    String text = resourceAdminServiceClient.getTextContent(
            PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME + "/" + TEST_COLLECTION1 + "/" + RESOURCE_NAME);
    String fileText = dh.getContent().toString();

    assertTrue(fileText.equalsIgnoreCase(text), PARENT_PATH + "/" + SYMLINK_PARENT_COLL_NAME + "/"
            + TEST_COLLECTION1 + "/" + RESOURCE_NAME + " creation failure");
}

From source file:net.sf.jclal.util.mail.SenderEmail.java

/**
 * Send the email with the indicated parameters
 *
 * @param subject The subject/*from   w w w. j  a va2s  . c o  m*/
 * @param content The content
 * @param reportFile The reportFile to send
 */
public void sendEmail(String subject, String content, File reportFile) {

    // Get system properties
    Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);

    if (!user.isEmpty() && !pass.isEmpty()) {

        properties.setProperty("mail.user", user);

        properties.setProperty("mail.password", pass);
    }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, toRecipients.toString());

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        if (attachReporFile) {

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile)));
            messageBodyPart.setFileName(reportFile.getName());
            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {

        Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:org.springframework.ws.transport.mail.MailSenderConnection.java

@Override
protected void onSendAfterWrite(WebServiceMessage message) throws IOException {
    Transport transport = null;// w w  w  .j  ava2  s .c om
    try {
        requestMessage.setDataHandler(
                new DataHandler(new ByteArrayDataSource(requestContentType, requestBuffer.toByteArray())));
        transport = session.getTransport(transportUri);
        transport.connect();
        requestMessage.saveChanges();
        transport.sendMessage(requestMessage, requestMessage.getAllRecipients());
    } catch (MessagingException ex) {
        throw new MailTransportException(ex);
    } finally {
        MailTransportUtils.closeService(transport);
    }
}

From source file:org.openhealthtools.openxds.repository.Utility.java

/**
 * Create a RepositoryItem containing provided content.
 *
 * @param id the id of the created ExtrinsicObject created for the RepositoryItem
 * @param content contents of the created RepositoryItem
 *
 * @return a <code>RepositoryItem</code> value
 * @throws IOException encountered during IO operations
 *///w ww .  j  av a  2  s  .c  o m
public XdsRepositoryItem createRepositoryItem(String id, String content) throws IOException {
    File file = createTempFile(content, true);

    DataHandler dh = new DataHandler(new FileDataSource(file));
    XdsRepositoryItem ri = new XdsRepositoryItemImpl(id, dh);
    return ri;
}

From source file:org.bimserver.tests.TestSimultaniousDownloadWithCaching.java

private void start() {
    BimServerConfig config = new BimServerConfig();
    Path homeDir = Paths.get("home");
    try {/*w  ww . j a  v  a2 s .c o  m*/
        if (Files.isDirectory(homeDir)) {
            PathUtils.removeDirectoryWithContent(homeDir);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    config.setClassPath(System.getProperty("java.class.path"));
    config.setHomeDir(homeDir);
    config.setPort(8080);
    config.setStartEmbeddedWebServer(true);
    config.setResourceFetcher(new LocalDevelopmentResourceFetcher(Paths.get("../")));
    final BimServer bimServer = new BimServer(config);
    try {
        LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), null);
        bimServer.start();
        if (bimServer.getServerInfo().getServerState() == ServerState.NOT_SETUP) {
            bimServer.getService(AdminInterface.class).setup("http://localhost", "Administrator",
                    "admin@bimserver.org", "admin", null, null, null);
        }
    } catch (PluginException e2) {
        e2.printStackTrace();
    } catch (ServerException e) {
        e.printStackTrace();
    } catch (DatabaseInitException e) {
        e.printStackTrace();
    } catch (BimserverDatabaseException e) {
        e.printStackTrace();
    } catch (DatabaseRestartRequiredException e) {
        e.printStackTrace();
    } catch (UserException e) {
        e.printStackTrace();
    }

    try {
        final ServiceMap serviceMap = bimServer.getServiceFactory().get(AccessMethod.INTERNAL);
        ServiceInterface serviceInterface = serviceMap.get(ServiceInterface.class);
        SettingsInterface settingsInterface = serviceMap.get(SettingsInterface.class);
        final AuthInterface authInterface = serviceMap.get(AuthInterface.class);
        serviceInterface = bimServer.getServiceFactory()
                .get(authInterface.login("admin@bimserver.org", "admin"), AccessMethod.INTERNAL)
                .get(ServiceInterface.class);
        settingsInterface.setCacheOutputFiles(true);
        settingsInterface.setGenerateGeometryOnCheckin(false);
        final SProject project = serviceMap.getServiceInterface().addProject("test", "ifc2x3tc1");
        SDeserializerPluginConfiguration deserializerByName = serviceMap.getServiceInterface()
                .getDeserializerByName("IfcStepDeserializer");
        Path file = Paths.get("../TestData/data/AC11-Institute-Var-2-IFC.ifc");
        serviceInterface.checkin(project.getOid(), "test", deserializerByName.getOid(), file.toFile().length(),
                file.getFileName().toString(), new DataHandler(new FileDataSource(file.toFile())), false, true);
        final SProject projectUpdate = serviceMap.getServiceInterface().getProjectByPoid(project.getOid());
        ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS,
                new ArrayBlockingQueue<Runnable>(1000));
        for (int i = 0; i < 20; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        ServiceMap serviceMap2 = bimServer.getServiceFactory().get(
                                authInterface.login("admin@bimserver.org", "admin"), AccessMethod.INTERNAL);
                        SSerializerPluginConfiguration serializerPluginConfiguration = serviceMap
                                .getServiceInterface().getSerializerByName("Ifc2x3");
                        Long download = serviceMap2.getServiceInterface().download(
                                Collections.singleton(projectUpdate.getLastRevisionId()),
                                DefaultQueries.allAsString(), serializerPluginConfiguration.getOid(), true);
                        SDownloadResult downloadData = serviceMap2.getServiceInterface()
                                .getDownloadData(download);
                        if (downloadData.getFile()
                                .getDataSource() instanceof CacheStoringEmfSerializerDataSource) {
                            CacheStoringEmfSerializerDataSource c = (CacheStoringEmfSerializerDataSource) downloadData
                                    .getFile().getDataSource();
                            try {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                c.writeToOutputStream(baos, null);
                                System.out.println(baos.size());
                            } catch (SerializerException e) {
                                e.printStackTrace();
                            }
                        } else {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            IOUtils.copy(downloadData.getFile().getInputStream(), baos);
                            System.out.println(baos.size());
                        }
                        serviceMap2.getServiceInterface().cleanupLongAction(download);
                    } catch (ServerException e) {
                        e.printStackTrace();
                    } catch (UserException e) {
                        e.printStackTrace();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (PublicInterfaceNotFoundException e1) {
                        e1.printStackTrace();
                    }
                }
            });
        }
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.HOURS);
        bimServer.stop();
    } catch (ServerException e1) {
        e1.printStackTrace();
    } catch (UserException e1) {
        e1.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (PublicInterfaceNotFoundException e2) {
        e2.printStackTrace();
    }
}

From source file:lucee.runtime.net.mail.HtmlEmailImpl.java

/**
 * Embeds an URL in the HTML.//  w w  w  .j a v a 2 s .c o m
 *
 * <p>This method allows to embed a file located by an URL into
 * the mail body.  It allows, for instance, to add inline images
 * to the email.  Inline files may be referenced with a
 * <code>cid:xxxxxx</code> URL, where xxxxxx is the Content-ID
 * returned by the embed function.
 *
 * <p>Example of use:<br><code><pre>
 * HtmlEmail he = new HtmlEmail();
 * he.setHtmlMsg("&lt;html&gt;&lt;img src=cid:" +
 *  embed("file:/my/image.gif","image.gif") +
 *  "&gt;&lt;/html&gt;");
 * // code to set the others email fields (not shown)
 * </pre></code>
 *
 * @param url The URL of the file.
 * @param cid A String with the Content-ID of the file.
 * @param name The name that will be set in the filename header
 * field.
 * @throws EmailException when URL supplied is invalid
 *  also see javax.mail.internet.MimeBodyPart for definitions
 *
 */
public void embed(URL url, String cid, String name) throws EmailException {
    // verify that the URL is valid
    try {
        InputStream is = url.openStream();
        is.close();
    } catch (IOException e) {
        throw new EmailException("Invalid URL");
    }

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(new URLDataSource(url)));
        mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.addHeader("Content-ID", "<" + cid + ">");
        this.inlineImages.add(mbp);
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:ee.ria.xroad.opmonitordaemon.QueryRequestHandler.java

static DataHandler createAttachmentDataSource(byte[] payload, String cid, String contentType) {
    return new DataHandler(new ByteArrayDataSource(payload, contentType)) {
        @Override//from   w w  w  .j  a va2s  .  c om
        public String getName() {
            return cid;
        }
    };
}

From source file:MSMessage.java

protected void parse(InputStream is) throws MessagingException {
    // Create a buffered input stream for efficiency
    if (!(is instanceof ByteArrayInputStream) && !(is instanceof BufferedInputStream))
        is = new BufferedInputStream(is);

    // Load headerstore
    headers.load(is);/*from w  ww .  j av  a2  s . co m*/

    /*
     * Load the content into a byte[].
     * This byte[] is shared among the bodyparts.
     */
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int b;
        // XXX - room for performance improvement
        while ((b = is.read()) != -1)
            bos.write(b);
        content = bos.toByteArray();
    } catch (IOException ioex) {
        throw new MessagingException("IOException", ioex);
    }

    /*
     * Check whether this is multipart.
     */
    boolean isMulti = false;
    // check for presence of X-MS-Attachment header
    String[] att = getHeader("X-MS-Attachment");
    if (att != null && att.length > 0)
        isMulti = true;
    else {
        /*
         * Fall back to scanning the content.
         * We scan the content until we find a sequence that looks
         * like the start of a uuencoded block, i.e., "<newline>begin".
         * If found, we claim that this is a multipart message.
         */
        for (int i = 0; i < content.length; i++) {
            int b = content[i] & 0xff; // mask higher byte
            if (b == '\r' || b == '\n') {
                // start of a new line
                if ((i + 5) < content.length) {
                    // can there be a "begin" now?
                    String s = toString(content, i + 1, i + 6);
                    if (s.equalsIgnoreCase("begin")) {
                        isMulti = true;
                        break;
                    }
                }
            }
        }
    }

    if (isMulti) {
        type = "multipart/mixed";
        dh = new DataHandler(new MSMultipartDataSource(this, content));
    } else {
        type = "text/plain"; // charset = ?
        dh = new DataHandler(new MimePartDataSource(this));
    }

    modified = false;
}