Example usage for java.lang StringBuffer indexOf

List of usage examples for java.lang StringBuffer indexOf

Introduction

In this page you can find the example usage for java.lang StringBuffer indexOf.

Prototype

@Override
public int indexOf(String str) 

Source Link

Usage

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java

public void getConvertedLetter(StringBuffer textLetter, StringBuffer htmlLetter,
        ArrayList<String[]> phValuePairs) {
    String expr = "[#]{1}[a-zA-Z]+[:]{1}[a-zA-Z]+[#]{1}";
    Pattern p = Pattern.compile(expr);
    Matcher m = p.matcher(textLetter);
    int st_i = 0;
    int end_i = 0;
    boolean matched = false;
    while (m.find()) {
        String table = "";
        //  String woHash = "";
        table = m.group();//from   w w w .j a va 2  s  . c  o m
        //   woHash = table.substring(1, table.length() - 1);
        // String[] sp = woHash.split(":");
        for (int i = 0; i < phValuePairs.size(); i++) {
            if (table.equals("#" + phValuePairs.get(i)[0] + ":" + phValuePairs.get(i)[1] + "#")) {
                st_i = textLetter.indexOf(table);
                end_i = st_i + table.length();
                if (st_i >= 0) {
                    textLetter.replace(st_i, end_i, phValuePairs.get(i)[2]);
                    //moved in last m = p.matcher(textLetter);
                    //break;
                }
                st_i = htmlLetter.indexOf(table);
                end_i = st_i + table.length();
                if (st_i >= 0) {
                    htmlLetter.replace(st_i, end_i, phValuePairs.get(i)[2]);
                    //  break;
                }
                m = p.matcher(textLetter);
                matched = true;
                break;
            }
        }
        if (!matched) {
            st_i = textLetter.indexOf(table);
            end_i = st_i + table.length();
            if (st_i >= 0) {
                textLetter.replace(st_i, end_i, "@~" + table.substring(1, table.length() - 1) + "@~");
                //moved in last m = p.matcher(textLetter);
                //break;
            }
            st_i = htmlLetter.indexOf(table);
            end_i = st_i + table.length();
            if (st_i >= 0) {
                htmlLetter.replace(st_i, end_i, "@~" + table.substring(1, table.length() - 1) + "@~");
                //  break;
            }
            m = p.matcher(textLetter);

            matched = false;
        }
    }

}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java

private ItemNodeModel builderNode(Map<String, Integer> multiNodeIndex, Element el, EntityModel entity,
        String baseXpath, String xpath, boolean isPolyType, StringBuffer foreignKeyDeleteMessage,
        boolean isCreate, boolean isStaging, String language) throws Exception {
    Map<String, TypeModel> metaDataTypes = entity.getMetaDataTypes();
    String realType = el.getAttribute("xsi:type"); //$NON-NLS-1$
    if (isPolyType) {
        xpath += ("".equals(xpath) ? el.getNodeName() : "/" + el.getNodeName()); //$NON-NLS-1$//$NON-NLS-2$
        if (realType != null && realType.trim().length() > 0) {
            xpath += ":" + realType; //$NON-NLS-1$
        }//  w w w .java2  s. c o m
    } else {
        xpath += ("".equals(xpath) ? el.getNodeName() : "/" + el.getNodeName()); //$NON-NLS-1$//$NON-NLS-2$
    }
    String typePath;
    if ("".equals(baseXpath)) { //$NON-NLS-1$
        typePath = xpath.replaceAll("\\[\\d+\\]", ""); //$NON-NLS-1$//$NON-NLS-2$
    } else {
        typePath = (baseXpath + "/" + xpath).replaceAll("\\[\\d+\\]", ""); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
    }
    typePath = typePath.replaceAll(":" + realType + "$", ""); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
    ItemNodeModel nodeModel = new ItemNodeModel(el.getNodeName());

    TypeModel model = findTypeModelByTypePath(metaDataTypes, typePath, language);
    nodeModel.setTypePath(model.getTypePath());
    nodeModel.setHasVisiblueRule(model.isHasVisibleRule());
    nodeModel.setHide(model.isHide());
    nodeModel.setVisible(!model.isHide());
    String realXPath = xpath;
    if (isPolyType) {
        realXPath = realXPath.replaceAll(":\\w+", ""); //$NON-NLS-1$//$NON-NLS-2$
    }

    if (model.getMaxOccurs() > 1 || model.getMaxOccurs() == -1) {

        Integer index = multiNodeIndex.get(realXPath);
        if (index == null) {
            nodeModel.setIndex(1);
            multiNodeIndex.put(realXPath, 1);
        } else {
            nodeModel.setIndex(index + 1);
            multiNodeIndex.put(realXPath, nodeModel.getIndex());
        }
    }

    if (realType != null && realType.trim().length() > 0) {
        nodeModel.setRealType(el.getAttribute("xsi:type")); //$NON-NLS-1$
    }
    nodeModel.setLabel(model.getLabel(language));
    nodeModel.setDescription(model.getDescriptionMap().get(language));
    nodeModel.setName(el.getNodeName());
    if (model.getMinOccurs() == 1 && model.getMaxOccurs() == 1) {
        nodeModel.setMandatory(true);
    }
    String foreignKey = findTypeModelByTypePath(metaDataTypes, typePath, language).getForeignkey();
    if (foreignKey != null && foreignKey.trim().length() > 0) {
        // set foreignKeyBean
        model.setRetrieveFKinfos(true);
        String modelType = el.getAttribute("tmdm:type"); //$NON-NLS-1$
        if (modelType != null && modelType.trim().length() > 0) {
            nodeModel.setTypeName(modelType);
        }
        ForeignKeyBean fkBean = org.talend.mdm.webapp.browserecords.server.util.CommonUtil.getForeignKeyDesc(
                model, el.getTextContent(), true, modelType, getEntityModel(foreignKey.split("/")[0], language), //$NON-NLS-1$
                isStaging, language);
        if (fkBean != null) {
            String fkNotFoundMessage = fkBean.get("foreignKeyDeleteMessage"); //$NON-NLS-1$
            if (fkNotFoundMessage != null) {// fix bug TMDM-2757
                if (foreignKeyDeleteMessage.indexOf(fkNotFoundMessage) == -1) {
                    foreignKeyDeleteMessage.append(fkNotFoundMessage).append("\r\n"); //$NON-NLS-1$
                }
                return nodeModel;
            }
            nodeModel.setObjectValue(fkBean);
        }
    } else if (model.isSimpleType()) {
        nodeModel.setObjectValue(el.getTextContent());
        org.talend.mdm.webapp.browserecords.server.util.CommonUtil.migrationMultiLingualFieldValue(null, model,
                el, typePath, false, nodeModel);
    }
    if (isCreate && model.getDefaultValueExpression() != null
            && model.getDefaultValueExpression().trim().length() > 0) {
        nodeModel.setChangeValue(true);
    }

    NodeList children = el.getChildNodes();
    if (children != null && !model.isSimpleType()) {
        List<TypeModel> childModels;
        if (nodeModel.getRealType() != null && nodeModel.getRealType().trim().length() > 0) {
            childModels = ((ComplexTypeModel) model).getRealType(nodeModel.getRealType()).getSubTypes();
        } else {
            if (!model.isAbstract()) {
                childModels = ((ComplexTypeModel) model).getSubTypes();
                if (childModels.size() == 0 && children.item(0) != null) {
                    TypeModel parentModel = model.getParentTypeModel();
                    while (parentModel != null) {
                        if (model.getType().getTypeName().equals(parentModel.getType().getTypeName())) {
                            List<TypeModel> types = ((ComplexTypeModel) parentModel).getSubTypes();
                            String parentPath = model.getTypePath();

                            for (TypeModel typeModel : types) {
                                String path = parentPath + "/" + typeModel.getName(); //$NON-NLS-1$
                                TypeModel childModel = null;
                                if (typeModel.isSimpleType()) {
                                    childModel = new SimpleTypeModel(typeModel.getName(), typeModel.getType());
                                } else {
                                    childModel = new ComplexTypeModel(typeModel.getName(), typeModel.getType());
                                }
                                childModel.setAbstract(typeModel.isAbstract());
                                childModel.setXpath(path);
                                childModel.setTypePath(path);
                                childModel.setTypePathObject(
                                        new TypePath(path, new HashMap<String, List<String>>()));
                                childModel.setNillable(typeModel.isNillable());
                                childModel.setMinOccurs(typeModel.getMinOccurs());
                                childModel.setMaxOccurs(typeModel.getMaxOccurs());
                                childModel.setParentTypeModel(model);
                                childModels.add(childModel);
                                metaDataTypes.put(path, childModel);
                            }
                            isModelUpdated = true;
                            break;
                        }
                        parentModel = parentModel.getParentTypeModel();
                    }
                }
            } else {
                childModels = org.talend.mdm.webapp.browserecords.shared.ReusableType
                        .getDefaultReusableTypeChildren((ComplexTypeModel) model, nodeModel);
            }
        }
        for (TypeModel typeModel : childModels) { // display tree node according to the studio default configuration
            boolean existNodeFlag = false;
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                if (child.getNodeType() == Node.ELEMENT_NODE) {
                    String tem_typePath;
                    if (realType != null && realType.trim().length() > 0) {
                        tem_typePath = typePath + ":" + realType + "/" + child.getNodeName(); //$NON-NLS-1$ //$NON-NLS-2$
                    } else {
                        tem_typePath = typePath + "/" + child.getNodeName(); //$NON-NLS-1$
                    }

                    if (typeModel.getTypePath().equals(tem_typePath) || (typeModel.getTypePathObject() != null
                            && typeModel.getTypePathObject().getAllAliasXpaths() != null
                            && typeModel.getTypePathObject().getAllAliasXpaths().contains(tem_typePath))) {
                        ItemNodeModel childNode = builderNode(multiNodeIndex, (Element) child, entity,
                                baseXpath, xpath, isPolyType, foreignKeyDeleteMessage, isCreate, isStaging,
                                language);
                        nodeModel.add(childNode);
                        existNodeFlag = true;
                        if (typeModel.getMaxOccurs() < 0 || typeModel.getMaxOccurs() > 1) {
                            continue;
                        } else {
                            break;
                        }
                    }
                }
            }
            if (!existNodeFlag) { // add default tree node when the node has not been saved in DB.
                nodeModel.add(org.talend.mdm.webapp.browserecords.server.util.CommonUtil
                        .getDefaultTreeModel(typeModel, isCreate, language).get(0));
            }
        }

    }
    for (String key : entity.getKeys()) {
        if (key.equals(realXPath)) {
            nodeModel.setKey(true);
        }
    }
    return nodeModel;

}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

public String updateCreateConstraint(Dialect dialect, StringBuffer buf, String name, Table table,
        Constraint constraint) {// w ww.  j a  v a 2  s  .  c o m
    NamingStrategy namingStrategy = getProfile().getNamingStrategy();
    String newName = namingStrategy.constraintName(constraint,
            getEntityClassName(namingStrategy.tableName(table.getName())));

    if (!name.equals(newName)) {
        String sqlCreate = buf.toString();
        Matcher matcher = CONSTRAINT_PATTERN.matcher(sqlCreate);
        if (matcher.find()) {
            buf = new StringBuffer();
            buf.append(sqlCreate.substring(0, matcher.start(1)));
            buf.append(newName);
            buf.append(sqlCreate.substring(matcher.end(1)));
        }
        name = newName;
    }

    String tableNameLC = getProfile().getNamingStrategy().tableName(table.getName()).toLowerCase();

    if (!renderTable(tableNameLC) || externalViews.contains(tableNameLC)) {
        return "-- skipped creation of constraint '" + name + "' for table '" + table.getName()
                + "' as the mapped entity was not chosen to be processed or is a view";
    }

    TableConfig tableConfig = tblNameToConfig.get(tableNameLC);

    String refTblNameLC = null;
    if (constraint instanceof ForeignKey) {
        if (tableConfig.getColumnNamesIsNoFK().contains(constraint.getColumn(0).getName().toLowerCase())) {
            return "-- skipped creation of foreign key constraint '" + name + "' for table '" + table.getName()
                    + "' according to annotation of type " + NoForeignKeyConstraint.class.getSimpleName();
        }
        refTblNameLC = getProfile().getNamingStrategy()
                .tableName(((ForeignKey) constraint).getReferencedTable().getName()).toLowerCase();
    }

    checkObjectName(dialect, name);
    String i18nFK = tableConfig.getI18nBaseEntityFkCol();

    if (i18nFK != null) {
        StringBuilder sql = new StringBuilder();
        tableNameLC = getI18NDetailTableName(tableNameLC);
        Matcher matcher = TBL_ALTER_PATTERN.matcher(buf.toString());
        if (matcher.find()) {
            sql.append(buf.substring(0, matcher.start(1))).append(tableNameLC)
                    .append(buf.substring(matcher.end(1)));
        }
        buf = new StringBuffer(sql.toString());
    }

    if (constraint instanceof ForeignKey) {
        StringBuilder colList = new StringBuilder();
        org.hibernate.mapping.Column singleColumn = null;

        TableConfig refTableConfig = tblNameToConfig.get(refTblNameLC);
        IntervalPartitioning refTblPart = refTableConfig != null
                ? refTableConfig.getTableAnnotationOfType(IntervalPartitioning.class)
                : null;

        for (org.hibernate.mapping.Column column : (Iterable<? extends org.hibernate.mapping.Column>) constraint
                .getColumns()) {
            if (colList.length() > 0) {
                colList.append(", ");
            }
            colList.append(column.getName().toLowerCase());
            singleColumn = singleColumn == null ? column : null;
        }

        if (externalViews.contains(refTblNameLC)) {
            buf = new StringBuffer("-- skipped creation of constraint '" + name + "' on table '" + tableNameLC
                    + "' since a view will be referenced");
        } else if (refTblPart != null && refTblPart.useLocalPK() && supportsPartitioning(dialect)) {
            buf = new StringBuffer();
            buf.append("-- skipped creation of foreign key constraint '").append(name).append("' on table '")
                    .append(tableNameLC).append("' to table '").append(refTblNameLC)
                    .append("' as the partitioned target table has a local PK (see @IntervalPartitioning on ")
                    .append(((ForeignKey) constraint).getReferencedEntityName()).append(")");
        } else {
            if (singleColumn != null) {
                if (tableConfig.getColumnNamesIsCascadeNullable()
                        .contains(singleColumn.getName().toLowerCase())) {
                    buf.append(" on delete set null");
                } else if (tableConfig.getColumnNamesIsCascadeDelete()
                        .contains(singleColumn.getName().toLowerCase()) && buf.indexOf("on delete") < 0) {
                    buf.append(" on delete cascade");
                }
            }

            Map<String, Deferrable> col2Deferrable = tableConfig.getColumnNameToDeferrable();
            Deferrable deferrable;
            if (supportsDeferrable(dialect) && col2Deferrable != null
                    && (deferrable = col2Deferrable.get(colList.toString())) != null) {
                buf.append(" deferrable");
                if (deferrable.initiallyDeferred()) {
                    buf.append(" initially deferred");
                }
            }

            if (getProfile().isDisableFKs()) {
                buf.insert(0,
                        "-- creating FK constraint initially disabled since we do not need it for profile '"
                                + getProfile() + "'\n");
                buf.append(" disable");
            }
        }

        getProfile().duplex(ObjectType.CONSTRAINT, name, buf.toString());

        if (constraint.getColumnSpan() == 1 && hasIndex(table, tableNameLC, singleColumn)) {
            LOG.debug("not creating foreign key index as there is already an index on table " + tableNameLC
                    + " and column " + colList.toString());
        } else {
            String fkIndexName = getProfile().getNamingStrategy().indexName(getEntityClassName(tableNameLC),
                    tableNameLC, DefaultNamingStrategy.concatColumnNames(colList.toString()));
            StringBuilder objDdl = new StringBuilder();
            objDdl.append("create index ").append(fkIndexName).append(" on ").append(tableNameLC).append(" (")
                    .append(colList.toString()).append(")");

            if (constraint.getColumnSpan() == 1) {
                tblColNameHasSingleColIndex.add(tableNameLC + "." + colList.toString());
            }

            buf.append(STATEMENT_SEPARATOR).append(objDdl);

            getProfile().duplex(ObjectType.INDEX, fkIndexName, objDdl.toString());
        }
    }

    return buf.toString();
}

From source file:com.xpn.xwiki.doc.XWikiDocument.java

/**
 * @param fieldname the name of the field to display
 * @param type the type of the field to display
 * @param pref the prefix to add in the field identifier in edit display for example
 * @param obj the object containing the field to display
 * @param wrappingSyntaxId the syntax of the content in which the result will be included. This to take care of some
 *            escaping depending of the syntax.
 * @param context the XWiki context//from   w  w  w  . ja v  a 2  s  .com
 * @return the rendered field
 */
public String display(String fieldname, String type, String pref, BaseObject obj, String wrappingSyntaxId,
        XWikiContext context) {
    if (obj == null) {
        return "";
    }

    boolean isInRenderingEngine = BooleanUtils.toBoolean((Boolean) context.get("isInRenderingEngine"));
    HashMap<String, Object> backup = new HashMap<String, Object>();
    try {
        backupContext(backup, context);
        setAsContextDoc(context);

        type = type.toLowerCase();
        StringBuffer result = new StringBuffer();
        PropertyClass pclass = (PropertyClass) obj.getXClass(context).get(fieldname);
        String prefix = pref
                + this.localEntityReferenceSerializer.serialize(obj.getXClass(context).getDocumentReference())
                + "_" + obj.getNumber() + "_";

        if (pclass == null) {
            return "";
        } else if (pclass.isCustomDisplayed(context)) {
            pclass.displayCustom(result, fieldname, prefix, type, obj, context);
        } else if (type.equals("view")) {
            pclass.displayView(result, fieldname, prefix, obj, context);
        } else if (type.equals("rendered")) {
            String fcontent = pclass.displayView(fieldname, prefix, obj, context);
            // This mode is deprecated for the new rendering and should also be removed for the old rendering
            // since the way to implement this now is to choose the type of rendering to do in the class itself.
            // Thus for the new rendering we simply make this mode work like the "view" mode.
            if (is10Syntax(wrappingSyntaxId)) {
                result.append(getRenderedContent(fcontent, getSyntaxId(), context));
            } else {
                result.append(fcontent);
            }
        } else if (type.equals("edit")) {
            context.addDisplayedField(fieldname);
            // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
            // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
            // escaping. For example for a textarea check the TextAreaClass class.
            if (is10Syntax(wrappingSyntaxId)) {
                // Don't use pre when not in the rendernig engine since for template we don't evaluate wiki syntax.
                if (isInRenderingEngine) {
                    result.append("{pre}");
                }
            }
            pclass.displayEdit(result, fieldname, prefix, obj, context);
            if (is10Syntax(wrappingSyntaxId)) {
                if (isInRenderingEngine) {
                    result.append("{/pre}");
                }
            }
        } else if (type.equals("hidden")) {
            // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
            // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
            // escaping. For example for a textarea check the TextAreaClass class.
            if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
                result.append("{pre}");
            }
            pclass.displayHidden(result, fieldname, prefix, obj, context);
            if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
                result.append("{/pre}");
            }
        } else if (type.equals("search")) {
            // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
            // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
            // escaping. For example for a textarea check the TextAreaClass class.
            if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
                result.append("{pre}");
            }
            prefix = this.localEntityReferenceSerializer
                    .serialize(obj.getXClass(context).getDocumentReference()) + "_";
            pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context);
            if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
                result.append("{/pre}");
            }
        } else {
            pclass.displayView(result, fieldname, prefix, obj, context);
        }

        // If we're in new rendering engine we want to wrap the HTML returned by displayView() in
        // a {{html/}} macro so that the user doesn't have to do it.
        // We test if we're inside the rendering engine since it's also possible that this display() method is
        // called
        // directly from a template and in this case we only want HTML as a result and not wiki syntax.
        // TODO: find a more generic way to handle html macro because this works only for XWiki 1.0 and XWiki 2.0
        // Add the {{html}}{{/html}} only when result really contains html since it's not needed for pure text
        if (isInRenderingEngine && !is10Syntax(wrappingSyntaxId)
                && (result.indexOf("<") != -1 || result.indexOf(">") != -1)) {
            result.insert(0, "{{html clean=\"false\" wiki=\"false\"}}");
            result.append("{{/html}}");
        }

        return result.toString();
    } catch (Exception ex) {
        // TODO: It would better to check if the field exists rather than catching an exception
        // raised by a NPE as this is currently the case here...
        LOGGER.warn(
                "Failed to display field [" + fieldname + "] in [" + type + "] mode for Object of Class ["
                        + this.defaultEntityReferenceSerializer.serialize(obj.getDocumentReference()) + "]",
                ex);
        return "";
    } finally {
        restoreContext(backup, context);
    }
}

From source file:org.pentaho.di.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr) {
    File masterZipfile = null;/*from   ww w  . ja v a 2 s . c  o  m*/

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        logError(BaseMessages.getString(PKG, "JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port)) {
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    }

    if (log.isDebug()) {
        props.put("mail.debug", "true");
    }

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(log.isDebug());

    try {
        // create a message
        Message msg = new MimeMessage(session);

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
            msg.setHeader("Sensitivity", sensitivity);
            // Possible values are normal, personal, private, company-confidential

        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name)) {
                sender_address = sender_name + '<' + sender_address + '>';
            }
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(BaseMessages.getString(PKG, "JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++) {
                address[i] = new InternetAddress(reply_Address_List[i]);
            }
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String[] destinations = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++) {
            address[i] = new InternetAddress(destinations[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, address);

        String realCC = environmentSubstitute(getDestinationCc());
        if (!Const.isEmpty(realCC)) {
            // Split the mail-address Cc: space separated
            String[] destinationsCc = realCC.split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++) {
                addressCc[i] = new InternetAddress(destinationsCc[i]);
            }

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        String realBCc = environmentSubstitute(getDestinationBCc());
        if (!Const.isEmpty(realBCc)) {
            // Split the mail-address BCc: space separated
            String[] destinationsBCc = realBCc.split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++) {
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);
            }

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();
        String endRow = isUseHTML() ? "<br>" : Const.CR;
        String realComment = environmentSubstitute(comment);
        if (!Const.isEmpty(realComment)) {
            messageText.append(realComment).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Job")).append(endRow);
            messageText.append("-----").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getRepositoryDirectory()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntry") + "   : ")
                    .append(getName()).append(endRow);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(endRow).append(BaseMessages.getString(PKG, "JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(endRow).append(endRow);
        }
        if (!onlySendComment && result != null) {
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PreviousResult") + ":")
                    .append(endRow);
            messageText.append("-----------------").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRejected") + "       : ")
                    .append(result.getNrLinesRejected()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(endRow);
            messageText.append(endRow);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.ContactInfo") + " :")
                    .append(endRow);
            messageText.append("---------------------").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(endRow);
            messageText.append(endRow);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(endRow);
                messageText.append("------------------------").append(endRow);

                addBacktracking(jobTracker, messageText);
                if (isUseHTML()) {
                    messageText.replace(0, messageText.length(),
                            messageText.toString().replace(Const.CR, endRow));
                }
            }
        }

        MimeMultipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // Attached files counter
        int nrattachedFiles = 0;

        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }
        } else {
            part1.setText(messageText.toString());
        }

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType()) {
                                    found = true;
                                }
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(file.getName().getBaseName());

                                // insist on base64 to preserve line endings
                                files.addHeader("Content-Transfer-Encoding", "base64");

                                // add the part with the file in the BodyPart();
                                parts.addBodyPart(files);
                                nrattachedFiles++;
                                logBasic("Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType()) {
                                    found = true;
                                }
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                try {
                                    int c;
                                    while ((c = inputStream.read()) >= 0) {
                                        zipOutputStream.write(c);
                                    }
                                } finally {
                                    inputStream.close();
                                }
                                zipOutputStream.closeEntry();
                                nrattachedFiles++;
                                logBasic("Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        logError("Error zipping attachement files into file [" + masterZipfile.getPath()
                                + "] : " + e.toString());
                        logError(Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                logError("Unable to close attachement zip file archive : " + e.toString());
                                logError(Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in the data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }

        int nrEmbeddedImages = 0;
        if (embeddedimages != null && embeddedimages.length > 0) {
            FileObject imageFile = null;
            for (int i = 0; i < embeddedimages.length; i++) {
                String realImageFile = environmentSubstitute(embeddedimages[i]);
                String realcontenID = environmentSubstitute(contentids[i]);
                if (messageText.indexOf("cid:" + realcontenID) < 0) {
                    if (log.isDebug()) {
                        log.logDebug("Image [" + realImageFile + "] is not used in message body!");
                    }
                } else {
                    try {
                        boolean found = false;
                        imageFile = KettleVFS.getFileObject(realImageFile, this);
                        if (imageFile.exists() && imageFile.getType() == FileType.FILE) {
                            found = true;
                        } else {
                            log.logError("We can not find [" + realImageFile + "] or it is not a file");
                        }
                        if (found) {
                            // Create part for the image
                            MimeBodyPart messageBodyPart = new MimeBodyPart();
                            // Load the image
                            URLDataSource fds = new URLDataSource(imageFile.getURL());
                            messageBodyPart.setDataHandler(new DataHandler(fds));
                            // Setting the header
                            messageBodyPart.setHeader("Content-ID", "<" + realcontenID + ">");
                            // Add part to multi-part
                            parts.addBodyPart(messageBodyPart);
                            nrEmbeddedImages++;
                            log.logBasic("Image '" + fds.getName() + "' was embedded in message.");
                        }
                    } catch (Exception e) {
                        log.logError(
                                "Error embedding image [" + realImageFile + "] in message : " + e.toString());
                        log.logError(Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (imageFile != null) {
                            try {
                                imageFile.close();
                            } catch (Exception e) { /* Ignore */
                            }
                        }
                    }
                }
            }
        }

        if (nrEmbeddedImages > 0 && nrattachedFiles == 0) {
            // If we need to embedd images...
            // We need to create a "multipart/related" message.
            // otherwise image will appear as attached file
            parts.setSubType("related");
        }
        // put all parts together
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            String authPass = getPassword(authenticationPassword);

            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")), authPass);
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")), authPass);
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null) {
                transport.close();
            }
        }
    } catch (IOException e) {
        logError("Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        logError("Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    logError("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        logError("         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    logError("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        logError("         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        logError("         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}