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.bimserver.servlets.BimBotRunner.java

public BimBotsOutput runBimBot() throws UserException, IOException {
    BimBotContext bimBotContext = new BimBotContext() {
        @Override/*from w w w.  j a v  a2 s . co m*/
        public void updateProgress(String label, int percentage) {
            if (streamingSocketInterface != null) {
                ObjectNode message = objectMapper.createObjectNode();
                message.put("type", "progress");
                message.put("topicId", topicId);
                ObjectNode payload = objectMapper.createObjectNode();
                payload.put("progress", percentage);
                payload.put("label", label);
                message.set("payload", payload);
                streamingSocketInterface.send(message);
            }
        }

        public String getCurrentUser() {
            return authorization.getUsername();
        }

        public String getContextId() {
            return contextId;
        }
    };

    try (DatabaseSession session = bimServer.getDatabase().createSession()) {
        ServiceMap serviceMap = bimServer.getServiceFactory().get(authorization, AccessMethod.INTERNAL);
        ServiceInterface serviceInterface = serviceMap.get(ServiceInterface.class);
        if (bimServer.getServerSettingsCache().getServerSettings().isStoreServiceRuns()) {
            LOGGER.info("Storing intermediate results");
            long start = System.nanoTime();
            // When we store service runs, we can just use the streaming deserializer to stream directly to the database, after that we'll trigger the actual service

            // Create or find project and link user and service to project
            // Checkin stream into project
            // Trigger service

            byte[] data = null;
            if (bimBotsServiceInterface.needsRawInput()) {
                // We need the raw input later on, lets just get it now
                data = ByteStreams.toByteArray(inputStream);
                // Make a clean inputstream that uses the data as the original won't be available after this
                inputStream = new ByteArrayInputStream(data);
            }

            SchemaName schema = SchemaName.valueOf(inputType);
            String projectSchema = getProjectSchema(serviceInterface, schema);

            SProject project = null;
            String uuid = contextId;
            if (uuid != null) {
                project = serviceInterface.getProjectByUuid(uuid);
            } else {
                project = serviceInterface.addProject("tmp-" + new Random().nextInt(), projectSchema);
            }

            SDeserializerPluginConfiguration deserializer = serviceInterface
                    .getSuggestedDeserializerForExtension("ifc", project.getOid());
            if (deserializer == null) {
                throw new BimBotsException("No deserializer found", BimBotDefaultErrorCode.NO_DESERIALIZER);
            }
            Long topicId = serviceInterface.initiateCheckin(project.getOid(), deserializer.getOid());
            ProgressTopic progressTopic = null;
            VirtualEndPoint virtualEndpoint = null;
            try {
                progressTopic = bimServer.getNotificationsManager().getProgressTopic(topicId);
                virtualEndpoint = new VirtualEndPoint() {
                    @Override
                    public NotificationInterface getNotificationInterface() {
                        return new NotificationInterfaceAdaptor() {
                            @Override
                            public void progress(Long topicId, SLongActionState state)
                                    throws UserException, ServerException {
                                bimBotContext.updateProgress(state.getTitle(), state.getProgress());
                            }
                        };
                    }
                };
                progressTopic.register(virtualEndpoint);
            } catch (TopicRegisterException e1) {
                e1.printStackTrace();
            }
            serviceInterface.checkinInitiatedSync(topicId, project.getOid(), "Auto checkin",
                    deserializer.getOid(), -1L, "s", new DataHandler(new InputStreamDataSource(inputStream)),
                    false);
            project = serviceInterface.getProjectByPoid(project.getOid());

            PackageMetaData packageMetaData = bimServer.getMetaDataManager()
                    .getPackageMetaData(project.getSchema());
            BasicIfcModel model = new BasicIfcModel(packageMetaData, null);
            model.setPluginClassLoaderProvider(bimServer.getPluginManager());
            try {
                Revision revision = session.get(project.getLastRevisionId(), OldQuery.getDefault());
                session.getMap(model, new OldQuery(packageMetaData, project.getId(), revision.getId(),
                        revision.getOid(), Deep.NO));
                model.getModelMetaData().setIfcHeader(revision.getLastConcreteRevision().getIfcHeader());
            } catch (BimserverDatabaseException e) {
                e.printStackTrace();
            }

            BimServerBimBotsInput input = new BimServerBimBotsInput(bimServer, authorization.getUoid(),
                    inputType, data, model, false);
            BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, bimBotContext, settings);
            long end = System.nanoTime();

            if (output.getModel() != null) {
                SerializerPlugin plugin = bimServer.getPluginManager()
                        .getSerializerPlugin("org.bimserver.ifc.step.serializer.Ifc2x3tc1StepSerializerPlugin");
                Serializer serializer = plugin.createSerializer(new PluginConfiguration());
                serializer.init(output.getModel(), new ProjectInfo(), true);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                serializer.writeToOutputStream(baos, null);
                output.setData(baos.toByteArray());
                output.setContentType("application/ifc");
            }

            SExtendedData extendedData = new SExtendedData();
            SFile file = new SFile();
            file.setData(output.getData());
            file.setFilename(output.getContentDisposition());
            file.setMime(output.getContentType());
            file.setSize(output.getData().length);
            Long fileId = serviceInterface.uploadFile(file);
            extendedData.setTimeToGenerate((end - start) / 1000000);
            extendedData.setFileId(fileId);
            extendedData.setTitle(output.getTitle());
            SExtendedDataSchema extendedDataSchema = null;
            try {
                extendedDataSchema = serviceInterface.getExtendedDataSchemaByName(output.getSchemaName());
            } catch (UserException e) {
                extendedDataSchema = new SExtendedDataSchema();
                extendedDataSchema.setContentType(output.getContentType());
                extendedDataSchema.setName(output.getSchemaName());
                serviceInterface.addExtendedDataSchema(extendedDataSchema);
            }
            extendedData.setSchemaId(extendedDataSchema.getOid());
            serviceInterface.addExtendedDataToRevision(project.getLastRevisionId(), extendedData);

            output.setContextId(project.getUuid());

            if (progressTopic != null) {
                try {
                    progressTopic.unregister(virtualEndpoint);
                } catch (TopicRegisterException e) {
                    e.printStackTrace();
                }
            }

            return output;
        } else {
            // When we don't store the service runs, there is no other way than to just use the old deserializer and run the service from the EMF model
            LOGGER.info("NOT Storing intermediate results");

            String projectSchema = getProjectSchema(serviceInterface, SchemaName.valueOf(inputType));

            Schema schema = Schema.valueOf(projectSchema.toUpperCase());
            DeserializerPlugin deserializerPlugin = bimServer.getPluginManager().getFirstDeserializer("ifc",
                    schema, true);
            if (deserializerPlugin == null) {
                throw new BimBotsException("No deserializer plugin found",
                        BimBotDefaultErrorCode.NO_DESERIALIZER);
            }

            byte[] data = IOUtils.toByteArray(inputStream);

            Deserializer deserializer = deserializerPlugin.createDeserializer(new PluginConfiguration());
            PackageMetaData packageMetaData = bimServer.getMetaDataManager().getPackageMetaData(schema.name());
            deserializer.init(packageMetaData);
            IfcModelInterface model = deserializer.read(new ByteArrayInputStream(data), inputType, data.length,
                    null);

            BimServerBimBotsInput input = new BimServerBimBotsInput(bimServer, authorization.getUoid(),
                    inputType, data, model, true);
            BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, bimBotContext,
                    new PluginConfiguration(foundService.getSettings()));

            return output;
        }
    } catch (BimBotsException e) {
        ObjectNode errorNode = OBJECT_MAPPER.createObjectNode();
        errorNode.put("code", e.getErrorCode());
        errorNode.put("message", e.getMessage());
        BimBotsOutput bimBotsOutput = new BimBotsOutput("ERROR", errorNode.toString().getBytes(Charsets.UTF_8));
        return bimBotsOutput;
    } catch (Throwable e) {
        LOGGER.error("", e);
        ObjectNode errorNode = OBJECT_MAPPER.createObjectNode();
        errorNode.put("code", 500);

        // TODO should not leak this much info to called, but for now this is useful debugging info
        errorNode.put("message", "Unknown error: " + e.getMessage());
        BimBotsOutput bimBotsOutput = new BimBotsOutput("ERROR", errorNode.toString().getBytes(Charsets.UTF_8));
        return bimBotsOutput;
    }
}

From source file:com.email.SendEmail.java

/**
 * Sends a single email and uses account based off of the section that the
 * email comes from after email is sent the attachments are gathered
 * together and collated into a single PDF file and a history entry is
 * created based off of that entry//  ww w .j av  a 2  s .c om
 *
 * @param eml EmailOutModel
 */
public static void sendEmails(EmailOutModel eml) {
    SystemEmailModel account = null;

    String section = eml.getSection();
    if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED")
            || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) {
        section = eml.getCaseType();
    }

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(section)) {
            account = acc;
            break;
        }
    }

    //Account Exists?
    if (account != null) {
        //Case Location
        String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG"))
                ? FileService.getCaseFolderORGCSCLocation(eml)
                : FileService.getCaseFolderLocation(eml);

        //Attachment List
        boolean allFilesExists = true;
        List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId());

        for (EmailOutAttachmentModel attach : attachmentList) {
            File attachment = new File(casePath + attach.getFileName());
            boolean exists = attachment.exists();
            if (exists == false) {
                allFilesExists = false;
                SECExceptionsModel item = new SECExceptionsModel();
                item.setClassName("SendEmail");
                item.setMethodName("sendEmails");
                item.setExceptionType("FileMissing");
                item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId()
                        + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator()
                        + "File: " + attachment);

                ExceptionHandler.HandleNoException(item);

                break;
            } else {
                if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))
                        || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) {
                    if (!attachment.renameTo(attachment)) {
                        allFilesExists = false;
                        SECExceptionsModel item = new SECExceptionsModel();
                        item.setClassName("SendEmail");
                        item.setMethodName("sendEmails");
                        item.setExceptionType("File In Use");
                        item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId()
                                + System.lineSeparator() + "EmailSubject: " + eml.getSubject()
                                + System.lineSeparator() + "File: " + attachment);

                        ExceptionHandler.HandleNoException(item);
                        break;
                    }
                }
            }
        }

        if (allFilesExists) {
            //Set up Initial Merge Utility
            PDFMergerUtility ut = new PDFMergerUtility();

            //List ConversionPDFs To Delete Later
            List<String> tempPDFList = new ArrayList<>();

            //create email message body
            Date emailSentTime = new Date();
            String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime);

            //Add Email Body To PDF Merge
            try {
                ut.addSource(casePath + emailPDFname);
                tempPDFList.add(casePath + emailPDFname);
            } catch (FileNotFoundException ex) {
                ExceptionHandler.Handle(ex);
            }

            //Get parts
            String FromAddress = account.getEmailAddress();
            String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";"));
            String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";"));
            String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";"));
            String emailSubject = eml.getSubject();
            String emailBody = eml.getBody();

            //Set Email Parts
            Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
            Properties properties = EmailProperties.setEmailOutProperties(account);
            Session session = Session.getInstance(properties, auth);
            MimeMessage smessage = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            //Add Parts to Email Message
            try {
                smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
                for (String To : TOAddressess) {
                    if (EmailValidator.getInstance().isValid(To)) {
                        smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                    }
                }
                for (String CC : CCAddressess) {
                    if (EmailValidator.getInstance().isValid(CC)) {
                        smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC));
                    }
                }
                for (String BCC : BCCAddressess) {
                    if (EmailValidator.getInstance().isValid(BCC)) {
                        smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
                    }
                }
                smessage.setSubject(emailSubject);

                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(emailBody, "text/plain");
                multipart.addBodyPart(messageBodyPart);

                //get attachments
                for (EmailOutAttachmentModel attachment : attachmentList) {
                    String fileName = attachment.getFileName();
                    String extension = FilenameUtils.getExtension(fileName);

                    //Convert attachments to PDF
                    //If Image
                    if (FileService.isImageFormat(fileName)) {
                        fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Word Doc
                    } else if (extension.equals("docx") || extension.equals("doc")) {
                        fileName = WordToPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Text File
                    } else if ("txt".equals(extension)) {
                        fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If PDF
                    } else if (FilenameUtils.getExtension(fileName).equals("pdf")) {

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }
                    }

                    DataSource source = new FileDataSource(casePath + fileName);
                    messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(fileName);
                    multipart.addBodyPart(messageBodyPart);
                }
                smessage.setContent(multipart);

                //Send Message
                if (Global.isOkToSendEmail()) {
                    Transport.send(smessage);
                } else {
                    Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject);
                }

                //DocumentFileName
                String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject())
                        .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf";

                //Set Merge File Destination
                ut.setDestinationFileName(casePath + savedDoc);

                //Try to Merge
                try {
                    ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
                } catch (IOException ex) {
                    ExceptionHandler.Handle(ex);
                }

                //Add emailBody Activity
                addEmailActivity(eml, savedDoc, emailSentTime);

                //Copy to related case folders
                if (section.equals("MED")) {
                    List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml);
                    if (relatedMedList.size() > 0) {
                        for (RelatedCaseModel related : relatedMedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                } else {
                    //This is blanket and should grab all related cases. (UNTESTED outside of CMDS)
                    List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml);
                    if (relatedList.size() > 0) {
                        for (EmailOutRelatedCaseModel related : relatedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationEmailOutRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                }

                //Clean SQL entries
                EmailOut.deleteEmailEntry(eml.getId());
                EmailOutAttachment.deleteAttachmentsForEmail(eml.getId());
                EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId());

                //Clean up temp PDFs
                for (String tempPDF : tempPDFList) {
                    new File(tempPDF).delete();
                }

            } catch (AddressException ex) {
                ExceptionHandler.Handle(ex);
            } catch (MessagingException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Convert a FileItem to a BodyPart// w w  w  .  j a va 2 s. co m
 *
 * @param item
 * @return message body part
 * @throws MessagingException
 */
public static BodyPart fileitemToBodypart(FileItem item) throws MessagingException {
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileItemDataStore(item);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(source.getName());
    return messageBodyPart;
}

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

private void sendIcalMessage() throws Exception {

    log.debug("sendIcalMessage");

    // Evaluating Configuration Data
    String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value();
    String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value();
    // String from = "openmeetings@xmlcrm.org";
    String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value();

    String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value();
    String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", smtpPort);

    Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable");
    if (conf != null) {
        if (conf.getConf_value().equals("1")) {
            props.put("mail.smtp.starttls.enable", "true");
        }//from w  w  w  .  j av a 2 s  .c  o m
    }

    // Check for Authentification
    Session session = null;
    if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null
            && emailUserpass.length() > 0) {
        // use SMTP Authentication
        props.put("mail.smtp.auth", "true");
        session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass));
    } else {
        // not use SMTP Authentication
        session = Session.getDefaultInstance(props, null);
    }

    // Building MimeMessage
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setFrom(new InternetAddress(from));
    mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

    // -- Create a new message --
    BodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\"")));

    Multipart multipart = new MimeMultipart();

    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource(
            new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    iCalAttachment.setFileName("invite.ics");

    multipart.addBodyPart(iCalAttachment);
    multipart.addBodyPart(msg);

    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(multipart);

    // -- Set some other header information --
    // mimeMessage.setHeader("X-Mailer", "XML-Mail");
    // mimeMessage.setSentDate(new Date());

    // Transport trans = session.getTransport("smtp");
    Transport.send(mimeMessage);

}

From source file:com.consol.citrus.ws.message.SoapAttachment.java

/**
 * Resolve dynamic string content in attachment
 * @param context Test context used to resolve dynamic content
 *//*from   w  ww. ja  v  a 2  s  .c  o  m*/
public void resolveDynamicContent(TestContext context) {
    resolvedContent = null;

    final String resolvedContentId = (contentId != null ? context.replaceDynamicContentInString(contentId)
            : null);
    final String resolvedContentType = (contentType != null ? context.replaceDynamicContentInString(contentType)
            : null);
    final String resolvedCharsetName = (charsetName != null ? context.replaceDynamicContentInString(charsetName)
            : null);

    if (StringUtils.hasText(content)) {
        resolvedContent = context.replaceDynamicContentInString(content);
    } else if (contentResourcePath != null) {
        try {
            if (resolvedContentType != null && resolvedContentType.startsWith("text/")) {
                resolvedContent = context.replaceDynamicContentInString(
                        FileUtils.readToString(FileUtils.getFileResource(contentResourcePath, context)));
            } else {
                final String resolvedContentResourcePath = context
                        .replaceDynamicContentInString(contentResourcePath);
                dataHandler = new DataHandler(new FileResourceDataSource(resolvedContentType,
                        resolvedContentResourcePath, resolvedContentId));
            }
        } catch (IOException e) {
            throw new CitrusRuntimeException(e);
        }
    }

    if (resolvedContent != null) {
        // Text content
        dataHandler = new DataHandler(new ContentDataSource(resolvedContentType, resolvedContent,
                resolvedCharsetName, resolvedContentId));
    }
}

From source file:org.igov.io.mail.Mail.java

public Mail _Attach(URL oURL, String sName) {
    try {/*  w  w w.j  a v  a2s. c o  m*/
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        DataSource oDataSource = new URLDataSource(oURL);
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        //oPart.setFileName(MimeUtility.encodeText(source.getName()));
        oMimeBodyPart.setFileName(
                MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("(sName={})", sName);
    } catch (Exception oException) {
        LOG.error("FAIL: {} (sName={})", oException.getMessage(), sName);
        LOG.trace("FAIL:", oException);
    }
    return this;
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;/*  w  w w .  ja  v a 2s.com*/
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            session = Session.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}

From source file:org.apache.synapse.transport.base.BaseUtils.java

/**
 * Handle a non SOAP and non XML message, and create a SOAPEnvelope to hold the
 * pure text or binary content as necessary
 *
 * @param msgContext the axis message context
 * @param message the legacy message//from w w  w.ja  va  2s . co m
 * @return the SOAP envelope
 */
private SOAPEnvelope handleLegacyMessage(MessageContext msgContext, Object message) {

    SOAPFactory soapFactory = new SOAP11Factory();
    SOAPEnvelope envelope = null;

    if (log.isDebugEnabled()) {
        log.debug("Non SOAP/XML message received");
    }

    // pick the name of the element that will act as the wrapper element for the
    // non-xml payload. If service doesn't define one, default
    Parameter wrapperParam = msgContext.getAxisService().getParameter(BaseConstants.WRAPPER_PARAM);

    QName wrapperQName = null;
    OMElement wrapper = null;
    if (wrapperParam != null) {
        wrapperQName = BaseUtils.getQNameFromString(wrapperParam.getValue());
    }

    String textPayload = getMessageTextPayload(message);
    if (textPayload != null) {
        OMTextImpl textData = (OMTextImpl) soapFactory.createOMText(textPayload);

        if (wrapperQName == null) {
            wrapperQName = BaseConstants.DEFAULT_TEXT_WRAPPER;
        }
        wrapper = soapFactory.createOMElement(wrapperQName, null);
        wrapper.addChild(textData);

    } else {
        byte[] msgBytes = getMessageBinaryPayload(message);
        if (msgBytes != null) {
            DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(msgBytes));
            OMText textData = soapFactory.createOMText(dataHandler, true);
            if (wrapperQName == null) {
                wrapperQName = BaseConstants.DEFAULT_BINARY_WRAPPER;
            }
            wrapper = soapFactory.createOMElement(wrapperQName, null);
            wrapper.addChild(textData);
            msgContext.setDoingMTOM(true);

        } else {
            handleException("Unable to read payload from message of type : " + message.getClass().getName());
        }
    }

    envelope = soapFactory.getDefaultEnvelope();
    envelope.getBody().addChild(wrapper);

    return envelope;
}

From source file:com.zimbra.cs.mailbox.MailboxTestUtil.java

public static ParsedMessage generateMessageWithAttachment(String subject) throws Exception {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    mm.setHeader("From", "Vera Oliphant <oli@example.com>");
    mm.setHeader("To", "Jimmy Dean <jdean@example.com>");
    mm.setHeader("Subject", subject);
    mm.setText("Good as gold");
    MimeMultipart multi = new ZMimeMultipart("mixed");
    ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT);
    cdisp.setParameter("filename", "fun.txt");

    ZMimeBodyPart bp = new ZMimeBodyPart();
    // MimeBodyPart.setDataHandler() invalidates Content-Type and CTE if there is any, so make sure
    // it gets called before setting Content-Type and CTE headers.
    try {/*  w w w. ja  v a  2  s.c o m*/
        bp.setDataHandler(new DataHandler(new ByteArrayDataSource("Feeling attached.", "text/plain")));
    } catch (IOException e) {
        throw new MessagingException("could not generate mime part content", e);
    }
    bp.addHeader("Content-Disposition", cdisp.toString());
    bp.addHeader("Content-Type", "text/plain");
    bp.addHeader("Content-Transfer-Encoding", MimeConstants.ET_8BIT);
    multi.addBodyPart(bp);

    mm.setContent(multi);
    mm.saveChanges();

    return new ParsedMessage(mm, false);
}

From source file:org.pentaho.platform.util.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {/* www  .  j a v a  2  s.c  o  m*/
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        final MimeMessage msg;

        if (EMBEDDED_HTML.equals(attachmentMimeType)) {

            //Message is ready
            msg = new MimeMessage(session, attachment);

            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");

                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);

                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }

                msg.setContent(newMultipart);
            }
        } else {

            // construct the message
            msg = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            if (attachment == null) {
                logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
                return false;
            }

            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

            if (body != null) {
                MimeBodyPart bodyMessagePart = new MimeBodyPart();
                bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(bodyMessagePart);
            }

            // attach the file to the message
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
            multipart.addBodyPart(attachmentBodyPart);

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}