Search in sources :

Example 66 with Binary

use of com.dexels.navajo.document.types.Binary in project navajo by Dexels.

the class CommonsMailMap method sendMail.

/**
 * This is where the actual mail is constructed and send
 * Inline images can be used through attachments
 * Annotation is cid:{?}. This will be replaced with cid:?
 * The first ? refers to the index number in the attachments starting with 0
 * The second ? will contain the generated id
 * EXAMPLE:
 * <hmtl>Some text <img src=\"cid:{0}\"></html>
 * The {0} will then be replaced with the first generated inline tag
 * @throws UserException
 */
public void sendMail() throws UserException {
    final ClassLoader current = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(javax.mail.Session.class.getClassLoader());
        // Create the email message and fill the basics
        HtmlEmail email = getNewHtmlEmail();
        if (debug) {
            email.setDebug(debug);
        }
        fillHtmlEmailBasics(email);
        // add attachments
        List<String> inlineImages = new ArrayList<>();
        if (this.attachments != null) {
            logger.debug("# of attachments found: {}", attachments.size());
            for (int i = 0; i < this.attachments.size(); i++) {
                AttachmentMapInterface am = this.attachments.get(i);
                String file = am.getAttachFile();
                String userFileName = am.getAttachFileName();
                Binary content = am.getAttachFileContent();
                String contentDisposition = am.getAttachContentDisposition();
                // Figure out how to get the path and then the url
                String fileName = "";
                if (content != null) {
                    fileName = content.getTempFileName(false);
                } else {
                    fileName = file;
                }
                File fl = new File(fileName);
                URL url = fl.toURI().toURL();
                logger.debug("Using url: {}", url);
                if (contentDisposition != null && contentDisposition.equalsIgnoreCase("Inline")) {
                    // embed the image and get the content id
                    inlineImages.add(email.embed(url, userFileName));
                } else {
                    email.attach(this.getEmailAttachment(fileName, url, contentDisposition, userFileName, userFileName));
                }
            }
        } else {
            logger.debug("No attachments");
        }
        logger.debug("Setting body, before replace: " + bodyText);
        // Replace any inline image tags with the created ones
        bodyText = replaceInlineImageTags(bodyText, inlineImages);
        // Finally set the complete html
        logger.debug("Setting body: {}", bodyText);
        email.setHtmlMsg(bodyText);
        // set the alternative message
        email.setTextMsg(this.getNonHtmlText());
        logger.info("Sending mail to {} cc: {} bcc: {} with subject: {}", to, cc, bcc, subject);
        // send the email
        email.send();
    } catch (Exception e) {
        if (ignoreFailures) {
            AuditLog.log("CommonsMailMap", e.getMessage(), e, Level.WARNING, myAccess.accessID);
            failure = e.getMessage();
        } else {
            AuditLog.log("CommonsMailMap", e.getMessage(), e, Level.SEVERE, myAccess.accessID);
            throw new UserException(-1, e.getMessage(), e);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(current);
    }
}
Also used : HtmlEmail(org.apache.commons.mail.HtmlEmail) ArrayList(java.util.ArrayList) AttachmentMapInterface(com.dexels.navajo.adapter.mailmap.AttachmentMapInterface) URL(java.net.URL) UserException(com.dexels.navajo.script.api.UserException) MappableException(com.dexels.navajo.script.api.MappableException) EmailException(org.apache.commons.mail.EmailException) Binary(com.dexels.navajo.document.types.Binary) UserException(com.dexels.navajo.script.api.UserException) File(java.io.File) Session(javax.mail.Session)

Example 67 with Binary

use of com.dexels.navajo.document.types.Binary in project navajo by Dexels.

the class HTTPMap method sendOverHTTP.

private final void sendOverHTTP() throws UserException {
    increaseInstanceCount();
    if (!isBelowInstanceThreshold()) {
        logger.warn("WARNING: More than 100 waiting HTTP requests");
    }
    logger.info("About to send to: {}", url);
    URL u = null;
    try {
        if (!url.startsWith("http://") && (!url.startsWith("https://"))) {
            logger.warn("No protocol. Always prepend protocol. Assuming http.");
            u = new URL("http://" + url);
        } else {
            u = new URL(url);
        }
    } catch (MalformedURLException e1) {
        throw new UserException("Malformed URL: " + url, e1);
    }
    try {
        HttpURLConnection con = createConnectionWithProxy(u);
        con.setConnectTimeout(connectTimeOut);
        if (readTimeOut != -1) {
            con.setReadTimeout(readTimeOut);
        }
        con.setRequestMethod(method);
        if (method.equals("POST") || method.equals("PUT") || method.equals("DELETE")) {
            con.setDoOutput(true);
            if (!method.equals("DELETE")) {
                con.setDoInput(true);
            }
        }
        con.setUseCaches(false);
        if (contentType != null) {
            con.setRequestProperty("Content-type", contentType);
        }
        if (contentLength > 0) {
            con.setRequestProperty("Content-length", contentLength + "");
        }
        // Add headers
        if (headers.size() > 0) {
            Iterator<String> keySet = headers.keySet().iterator();
            while (keySet.hasNext()) {
                String key = keySet.next();
                con.setRequestProperty(key, headers.get(key));
            }
        }
        if (textContent != null) {
            OutputStreamWriter osw = null;
            osw = new OutputStreamWriter(con.getOutputStream());
            try {
                osw.write(textContent);
            } finally {
                osw.close();
            }
        } else if (content != null && !method.equals("GET") && !method.equals("HEAD")) {
            OutputStream os = null;
            os = con.getOutputStream();
            try {
                content.write(os);
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        } else {
            if (method.equals("POST")) {
                logger.warn("Empty content.");
                throw new UserException(-1, "");
            }
        }
        responseCode = con.getResponseCode();
        responseMessage = con.getResponseMessage();
        responseContentType = con.getHeaderField("Content-Type");
        InputStream is = (responseCode < 400 ? con.getInputStream() : con.getErrorStream());
        if (responseCode > 299) {
            logger.warn("Got a {} response code back on call to {}: {}", responseCode, url, responseMessage);
        }
        try {
            result = new Binary(is);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } catch (java.net.SocketTimeoutException sto) {
        // 
        if (!catchConnectionTimeOut) {
            logger.error("Got connectiontimeout for url: {}", url);
            throw new UserException(-1, sto.getMessage(), sto);
        } else {
            logger.warn("Got connectiontimeout for url: {}", url);
            hasConnectionTimeOut = true;
        }
    } catch (Exception e) {
        throw new UserException(-1, e.getMessage(), e);
    } finally {
        decreaseInstanceCount();
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) URL(java.net.URL) UserException(com.dexels.navajo.script.api.UserException) MappableException(com.dexels.navajo.script.api.MappableException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) OutputStreamWriter(java.io.OutputStreamWriter) UserException(com.dexels.navajo.script.api.UserException) Binary(com.dexels.navajo.document.types.Binary)

Example 68 with Binary

use of com.dexels.navajo.document.types.Binary in project navajo by Dexels.

the class MailMapAlternative method sendMail.

private final void sendMail() throws UserException {
    retries++;
    try {
        String result = "";
        result = text;
        Properties props = System.getProperties();
        props.put("mail.smtp.host", mailServer);
        Session session = Session.getInstance(props);
        javax.mail.Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(sender));
        InternetAddress[] addresses = new InternetAddress[this.recipientArray.length];
        for (int i = 0; i < this.recipientArray.length; i++) {
            addresses[i] = new InternetAddress(this.recipientArray[i]);
        }
        msg.setRecipients(javax.mail.Message.RecipientType.TO, addresses);
        if (ccArray != null) {
            InternetAddress[] extra = new InternetAddress[this.ccArray.length];
            for (int i = 0; i < this.ccArray.length; i++) {
                extra[i] = new InternetAddress(this.ccArray[i]);
            }
            msg.setRecipients(javax.mail.Message.RecipientType.CC, extra);
        }
        if (bccArray != null) {
            InternetAddress[] extra = new InternetAddress[this.bccArray.length];
            for (int i = 0; i < this.bccArray.length; i++) {
                extra[i] = new InternetAddress(this.bccArray[i]);
            }
            msg.setRecipients(javax.mail.Message.RecipientType.BCC, extra);
        }
        msg.setSubject(subject);
        msg.setSentDate(new java.util.Date());
        // Use stylesheet if specified.
        if (!xslFile.equals("")) {
            java.io.File xsl = new java.io.File(xslFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            doc.write(bos);
            bos.close();
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            Document navajoDoc = XMLDocumentUtils.createDocument(bis, false);
            bis.close();
            result = XMLDocumentUtils.transform(navajoDoc, xsl);
        }
        if (attachments == null && contentType.equals("text/plain")) {
            msg.setText(result);
        } else {
            Multipart multipart = new MimeMultipart("mixed");
            BodyPart textBody = new MimeBodyPart();
            textBody.setContent(result, contentType);
            Multipart related = new MimeMultipart("related");
            related.addBodyPart(textBody);
            if (bodyparts != null && !bodyparts.isEmpty()) {
                // Put related bodyparts in related.
                for (int i = 0; i < bodyparts.size(); i++) {
                    AttachmentMapInterface am = bodyparts.get(i);
                    String file = am.getAttachFile();
                    String userFileName = am.getAttachFileName();
                    Binary content = am.getAttachFileContent();
                    String encoding = am.getEncoding();
                    String attachContentType = am.getAttachContentType();
                    MimeBodyPart bp = new MimeBodyPart();
                    logger.debug("Embedding: {}", userFileName);
                    if (file != null) {
                        if (userFileName == null) {
                            userFileName = file;
                        }
                        FileDataSource fileDatasource = new FileDataSource(file);
                        bp.setDataHandler(new DataHandler(fileDatasource));
                    } else if (content != null) {
                        BinaryDataSource bds = new BinaryDataSource(content, "");
                        DataHandler dh = new DataHandler(bds);
                        bp.setDataHandler(dh);
                        if (encoding != null) {
                            bp.setHeader("Content-Transfer-Encoding", encoding);
                            encoding = null;
                        }
                    }
                    bp.setFileName(userFileName);
                    if (attachContentType != null) {
                        bp.setHeader("Content-Type", attachContentType);
                    }
                    bp.setHeader("Content-ID", "<attach-nr-" + i + ">");
                    related.addBodyPart(bp);
                }
            }
            MimeBodyPart bop = new MimeBodyPart();
            bop.setContent(related);
            multipart.addBodyPart(bop);
            if (attachments != null) {
                for (int i = 0; i < attachments.size(); i++) {
                    AttachmentMapInterface am = attachments.get(i);
                    String file = am.getAttachFile();
                    String userFileName = am.getAttachFileName();
                    Binary content = am.getAttachFileContent();
                    String encoding = am.getEncoding();
                    String attachContentType = am.getAttachContentType();
                    String attachContentDisposition = am.getAttachContentDisposition();
                    MimeBodyPart bp = new MimeBodyPart();
                    logger.debug("Attaching: {}", userFileName);
                    if (file != null) {
                        if (userFileName == null) {
                            userFileName = file;
                        }
                        FileDataSource fileDatasource = new FileDataSource(file);
                        bp.setDataHandler(new DataHandler(fileDatasource));
                    } else if (content != null) {
                        BinaryDataSource bds = new BinaryDataSource(content, "");
                        DataHandler dh = new DataHandler(bds);
                        bp.setDataHandler(dh);
                        if (encoding != null) {
                            bp.setHeader("Content-Transfer-Encoding", encoding);
                        }
                    }
                    bp.setFileName(userFileName);
                    if (attachContentType != null) {
                        bp.setHeader("Content-Type", attachContentType);
                    }
                    bp.setDisposition(attachContentDisposition);
                    multipart.addBodyPart(bp);
                }
            }
            msg.setContent(multipart);
        }
        logger.info("Sending mail to {} cc: {} bcc: {} with subject: {}", recipients, cc, bcc, subject);
        Transport.send(msg);
    } catch (Exception e) {
        if (ignoreFailures) {
            AuditLog.log("MailMap", e.getMessage(), e, Level.WARNING, myAccess.accessID);
            failure = e.getMessage();
        } else {
            AuditLog.log("MailMap", e.getMessage(), e, Level.SEVERE, myAccess.accessID);
            throw new UserException(-1, e.getMessage());
        }
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Document(org.w3c.dom.Document) BinaryDataSource(com.dexels.navajo.datasource.BinaryDataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) UserException(com.dexels.navajo.script.api.UserException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AttachmentMapInterface(com.dexels.navajo.adapter.mailmap.AttachmentMapInterface) UserException(com.dexels.navajo.script.api.UserException) MappableException(com.dexels.navajo.script.api.MappableException) ByteArrayInputStream(java.io.ByteArrayInputStream) Binary(com.dexels.navajo.document.types.Binary) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 69 with Binary

use of com.dexels.navajo.document.types.Binary in project navajo by Dexels.

the class CSVMap method main.

public static void main(String[] args) throws Exception {
    Mappable csv = new CSVMap();
    ((CSVMap) csv).setSeparator(";");
    ((CSVMap) csv).setIncludeEmpty(true);
    ((CSVMap) csv).setSkipFirstRow(false);
    Binary b = new Binary(new File("C:/Temp/LedenLIJST-vertrouwelijktest.csv"));
    ((CSVMap) csv).setFileContent(b);
    Mappable[] all = ((CSVMap) csv).getEntries();
    for (int i = 0; i < all.length; i++) {
        CSVEntryMap entryMap = ((CSVEntryMap) all[i]);
        logger.info("a = >" + entryMap.getEntry(Integer.valueOf(0)) + "< - >" + entryMap.getEntry(Integer.valueOf(1)) + "< - >" + entryMap.getEntry(Integer.valueOf(2)) + "< - >" + entryMap.getEntry(Integer.valueOf(3)) + "< - >" + entryMap.getEntry(Integer.valueOf(4)) + "< - >" + entryMap.getEntry(Integer.valueOf(5)) + "< - >" + entryMap.getEntry(Integer.valueOf(6)) + "< - >" + entryMap.getEntry(Integer.valueOf(7)) + "< - >" + entryMap.getEntry(Integer.valueOf(8)) + "< - >" + entryMap.getEntry(Integer.valueOf(9)) + "< - >" + entryMap.getEntry(Integer.valueOf(10)) + "< - >" + entryMap.getEntry(Integer.valueOf(11)) + "<");
    }
}
Also used : Mappable(com.dexels.navajo.script.api.Mappable) CSVEntryMap(com.dexels.navajo.adapter.csvmap.CSVEntryMap) Binary(com.dexels.navajo.document.types.Binary) File(java.io.File)

Example 70 with Binary

use of com.dexels.navajo.document.types.Binary in project navajo by Dexels.

the class NavajoDomStreamer method create.

private static Prop create(Property tmlProperty) {
    String type = tmlProperty.getType();
    List<Select> selections = selectFromTml(tmlProperty.getAllSelections());
    String value = null;
    Binary binary = null;
    if (Property.BINARY_PROPERTY.equals(type)) {
        value = null;
        binary = (Binary) tmlProperty.getTypedValue();
    } else if (Property.SELECTION_PROPERTY.equals(type)) {
        value = null;
    } else {
        value = tmlProperty.getValue();
    }
    Optional<Direction> direction = "in".equals(tmlProperty.getDirection()) ? Optional.of(Direction.IN) : "out".equals(tmlProperty.getDirection()) ? Optional.of(Direction.OUT) : Optional.empty();
    return Prop.create(tmlProperty.getName(), value, tmlProperty.getType(), selections, direction, tmlProperty.getDescription(), tmlProperty.getLength(), tmlProperty.getSubType(), Optional.ofNullable(tmlProperty.getCardinality()), binary);
}
Also used : Select(com.dexels.navajo.document.stream.api.Select) Binary(com.dexels.navajo.document.types.Binary) Direction(com.dexels.navajo.document.stream.api.Prop.Direction)

Aggregations

Binary (com.dexels.navajo.document.types.Binary)139 Test (org.junit.Test)38 IOException (java.io.IOException)32 TMLExpressionException (com.dexels.navajo.expression.api.TMLExpressionException)26 File (java.io.File)25 Ignore (org.junit.Ignore)17 Property (com.dexels.navajo.document.Property)16 URL (java.net.URL)16 UserException (com.dexels.navajo.script.api.UserException)14 OutputStream (java.io.OutputStream)13 FileOutputStream (java.io.FileOutputStream)12 Navajo (com.dexels.navajo.document.Navajo)11 MappableException (com.dexels.navajo.script.api.MappableException)11 FileInputStream (java.io.FileInputStream)9 InputStream (java.io.InputStream)9 Message (com.dexels.navajo.document.Message)8 StringWriter (java.io.StringWriter)8 OutputStreamWriter (java.io.OutputStreamWriter)7 NavajoException (com.dexels.navajo.document.NavajoException)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6