Example usage for java.util Stack empty

List of usage examples for java.util Stack empty

Introduction

In this page you can find the example usage for java.util Stack empty.

Prototype

public boolean empty() 

Source Link

Document

Tests if this stack is empty.

Usage

From source file:com.autsia.bracer.BracerParser.java

/**
 * Evaluates once parsed math expression with "var" variable included
 *
 * @param variableValue User-specified <code>Double</code> value
 * @return <code>String</code> representation of the result
 * @throws <code>ParseException</code> if the input expression is not
 *                                     correct
 * @since 3.0/*w ww  .j  av a2s.c o  m*/
 */
public String evaluate(double variableValue) throws ParseException {
    /* check if is there something to evaluate */
    if (stackRPN.empty()) {
        return "";
    }

    /* clean answer stack */
    stackAnswer.clear();

    /* get the clone of the RPN stack for further evaluating */
    @SuppressWarnings("unchecked")
    Stack<String> stackRPN = (Stack<String>) this.stackRPN.clone();

    /* enroll the variable value into expression */
    Collections.replaceAll(stackRPN, VARIABLE, Double.toString(variableValue));

    /* evaluating the RPN expression */
    while (!stackRPN.empty()) {
        String token = stackRPN.pop();
        if (isNumber(token)) {
            stackAnswer.push(token);
        } else if (isOperator(token)) {
            Complex a = complexFormat.parse(stackAnswer.pop());
            Complex b = complexFormat.parse(stackAnswer.pop());
            boolean aBoolean = a.getReal() == 1.0;
            boolean bBoolean = b.getReal() == 1.0;
            switch (token) {
            case "+":
                stackAnswer.push(complexFormat.format(b.add(a)));
                break;
            case "-":
                stackAnswer.push(complexFormat.format(b.subtract(a)));
                break;
            case "*":
                stackAnswer.push(complexFormat.format(b.multiply(a)));
                break;
            case "/":
                stackAnswer.push(complexFormat.format(b.divide(a)));
                break;
            case "|":
                stackAnswer.push(String.valueOf(aBoolean || bBoolean ? "1" : "0"));
                break;
            case "&":
                stackAnswer.push(String.valueOf(aBoolean && bBoolean ? "1" : "0"));
                break;
            }
        } else if (isFunction(token)) {
            Complex a = complexFormat.parse(stackAnswer.pop());
            boolean aBoolean = a.getReal() == 1.0;
            switch (token) {
            case "abs":
                stackAnswer.push(complexFormat.format(a.abs()));
                break;
            case "acos":
                stackAnswer.push(complexFormat.format(a.acos()));
                break;
            case "arg":
                stackAnswer.push(complexFormat.format(a.getArgument()));
                break;
            case "asin":
                stackAnswer.push(complexFormat.format(a.asin()));
                break;
            case "atan":
                stackAnswer.push(complexFormat.format(a.atan()));
                break;
            case "conj":
                stackAnswer.push(complexFormat.format(a.conjugate()));
                break;
            case "cos":
                stackAnswer.push(complexFormat.format(a.cos()));
                break;
            case "cosh":
                stackAnswer.push(complexFormat.format(a.cosh()));
                break;
            case "exp":
                stackAnswer.push(complexFormat.format(a.exp()));
                break;
            case "imag":
                stackAnswer.push(complexFormat.format(a.getImaginary()));
                break;
            case "log":
                stackAnswer.push(complexFormat.format(a.log()));
                break;
            case "neg":
                stackAnswer.push(complexFormat.format(a.negate()));
                break;
            case "real":
                stackAnswer.push(complexFormat.format(a.getReal()));
                break;
            case "sin":
                stackAnswer.push(complexFormat.format(a.sin()));
                break;
            case "sinh":
                stackAnswer.push(complexFormat.format(a.sinh()));
                break;
            case "sqrt":
                stackAnswer.push(complexFormat.format(a.sqrt()));
                break;
            case "tan":
                stackAnswer.push(complexFormat.format(a.tan()));
                break;
            case "tanh":
                stackAnswer.push(complexFormat.format(a.tanh()));
                break;
            case "pow":
                Complex b = complexFormat.parse(stackAnswer.pop());
                stackAnswer.push(complexFormat.format(b.pow(a)));
                break;
            case "not":
                stackAnswer.push(String.valueOf(!aBoolean ? "1" : "0"));
                break;
            }
        }
    }

    if (stackAnswer.size() > 1) {
        throw new ParseException("Some operator is missing", 0);
    }

    return stackAnswer.pop();
}

From source file:com.calc.BracerParser.java

/**
 * Evaluates once parsed math expression with "var" variable included
 *
 * @param variableValue User-specified <code>Double</code> value
 * @return <code>String</code> representation of the result
 * @throws <code>ParseException</code> if the input expression is not
 *                                     correct
 * @since 3.0/*from   w  w w  . j a va  2s .  c om*/
 */
public String evaluate(double variableValue) throws ParseException {
    /* check if is there something to evaluate */
    if (stackRPN.empty()) {
        return "";
    }

    /* clean answer stack */
    stackAnswer.clear();

    /* get the clone of the RPN stack for further evaluating */
    @SuppressWarnings("unchecked")
    Stack<String> stackRPN = (Stack<String>) this.stackRPN.clone();

    /* enroll the variable value into expression */
    Collections.replaceAll(stackRPN, VARIABLE, Double.toString(variableValue));

    /* evaluating the RPN expression */
    while (!stackRPN.empty()) {
        String token = stackRPN.pop();
        if (isNumber(token)) {
            stackAnswer.push(token);
        } else if (isOperator(token)) {
            Complex a = complexFormat.parse(stackAnswer.pop());
            Complex b = complexFormat.parse(stackAnswer.pop());
            boolean aBoolean = a.getReal() == 1.0;
            boolean bBoolean = b.getReal() == 1.0;
            switch (token) {
            case "+":
                stackAnswer.push(complexFormat.format(b.add(a)));
                break;
            case "-":
                stackAnswer.push(complexFormat.format(b.subtract(a)));
                break;
            case "*":
                stackAnswer.push(complexFormat.format(b.multiply(a)));
                break;
            case "/":
                stackAnswer.push(complexFormat.format(b.divide(a)));
                break;
            case "|":
                stackAnswer.push(String.valueOf(aBoolean || bBoolean ? "1" : "0"));
                break;
            case "&":
                stackAnswer.push(String.valueOf(aBoolean && bBoolean ? "1" : "0"));
                break;
            }
        } else if (isFunction(token)) {
            Complex a = complexFormat.parse(stackAnswer.pop());
            boolean aBoolean = a.getReal() == 1.0;
            switch (token) {
            case "fat":
                stackAnswer.push(complexFormat.format(a.abs()));
                break;
            case "fib":
                stackAnswer.push(complexFormat.format(a.acos()));
                break;
            case "arg":
                stackAnswer.push(complexFormat.format(a.getArgument()));
                break;
            case "asin":
                stackAnswer.push(complexFormat.format(a.asin()));
                break;
            case "atan":
                stackAnswer.push(complexFormat.format(a.atan()));
                break;
            case "conj":
                stackAnswer.push(complexFormat.format(a.conjugate()));
                break;
            case "cos":
                stackAnswer.push(complexFormat.format(a.cos()));
                break;
            case "cosh":
                stackAnswer.push(complexFormat.format(a.cosh()));
                break;
            case "exp":
                stackAnswer.push(complexFormat.format(a.exp()));
                break;
            case "imag":
                stackAnswer.push(complexFormat.format(a.getImaginary()));
                break;
            case "log":
                stackAnswer.push(complexFormat.format(a.log()));
                break;
            case "neg":
                stackAnswer.push(complexFormat.format(a.negate()));
                break;
            case "real":
                stackAnswer.push(complexFormat.format(a.getReal()));
                break;
            case "sin":
                stackAnswer.push(complexFormat.format(a.sin()));
                break;
            case "sinh":
                stackAnswer.push(complexFormat.format(a.sinh()));
                break;
            case "sqrt":
                stackAnswer.push(complexFormat.format(a.sqrt()));
                break;
            case "tan":
                stackAnswer.push(complexFormat.format(a.tan()));
                break;
            case "tanh":
                stackAnswer.push(complexFormat.format(a.tanh()));
                break;
            case "pow":
                Complex b = complexFormat.parse(stackAnswer.pop());
                stackAnswer.push(complexFormat.format(b.pow(a)));
                break;
            case "not":
                stackAnswer.push(String.valueOf(!aBoolean ? "1" : "0"));
                break;
            }
        }
    }

    if (stackAnswer.size() > 1) {
        throw new ParseException("Some operator is missing", 0);
    }

    return stackAnswer.pop();
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * List the contents of directory.// www  . j  a  v  a  2  s  .  com
 * @param directory {@link File}
 * @param includingDirectory boolean
 * @return List<String> 
 * @throws IOException in case of error
 */
public static List<String> listDirectory(File directory, boolean includingDirectory) throws IOException {

    Stack<String> stack = new Stack<String>();
    List<String> list = new ArrayList<String>();

    // If it's a file, just return itself
    if (directory.isFile()) {
        if (directory.canRead()) {
            list.add(directory.getName());
        }
    } else {

        // Traverse the directory in width-first manner, no-recursively
        String root = directory.getParent();
        stack.push(directory.getName());
        while (!stack.empty()) {
            String current = (String) stack.pop();
            File curDir = new File(root, current);
            String[] fileList = curDir.list();
            if (fileList != null) {
                for (String entry : fileList) {
                    File file = new File(curDir, entry);
                    if (file.isFile()) {
                        if (file.canRead()) {
                            list.add(current + File.separator + entry);
                        } else {
                            throw new IOException("Can't read file: " + file.getPath());
                        }
                    } else if (file.isDirectory()) {
                        if (includingDirectory) {
                            list.add(current + File.separator + entry);
                        }
                        stack.push(current + File.separator + file.getName());
                    } else {
                        throw new IOException("Unknown entry: " + file.getPath());
                    }
                }
            }
        }
    }
    return list;
}

From source file:co.anarquianegra.rockolappServidor.mundo.ListaReproductor.java

/**
 * Agrega canciones de un usuario a la lista de reproduccion grande
 * notifica a la interfaz para mostrar un mensaje de que han
 * sido aadidas las canciones//from w w  w.j  a v  a  2s  . c  o  m
 * @param canciones
 * @param infoUsuario informacion del usuario
 */
synchronized public void agregarLista(Stack<Cancion> canciones, String infoUsuario) {
    for (int i = 0; i < canciones.size(); i++) {
        Cancion c = (Cancion) canciones.get(i);
    }
    while (!canciones.empty()) {
        try {
            listaReproduccion.add(canciones.pop());
        } catch (UnsupportedOperationException e) {
            System.out.println("Erro agregar cancion: " + e.toString());
        }
    }
    if (mediaPlayer == null && playing)
        reproducir();
    else if (mediaPlayer != null && mediaPlayer.getStatus().equals(Status.DISPOSED) && playing)
        reproducir();
    cantidadConexionesPositivas++;
}

From source file:org.sipfoundry.sipxconfig.cfgmgt.AgentRunner.java

/**
 * Run a full job at a location. Update job table for any failures in either running the
 * command or errors in stderr/*from   w  w  w  .  j a va 2 s  .  co  m*/
 */
void runJob(Location location, String label, String command) {
    PipedOutputStream log = null;
    Serializable job = m_jobContext.schedule(label, location);
    AgentResults results = new AgentResults();
    Stack<String> errs;
    try {
        m_jobContext.start(job);
        log = new PipedOutputStream();
        PipedInputStream in = new PipedInputStream(log);
        results.parse(in);
        int status = runCommand(command, log);
        errs = results.getResults(1000);
        if (errs.size() > 0) {
            String err = location.getFqdn() + ':' + errs.pop();
            ConfigManagerImpl.fail(m_jobContext, label, job, new ConfigException(err));
            while (!errs.empty()) {
                // Tricky alert - show additional errors as new jobs
                Serializable jobErr = m_jobContext.schedule(label, location);
                m_jobContext.start(jobErr);
                err = location.getFqdn() + ':' + errs.pop();
                ConfigManagerImpl.fail(m_jobContext, label, jobErr, new ConfigException(err));
            }
        } else if (status != 0 && errs.size() == 0) {
            String msg = format("Agent run on %s finshed but returned error code %d", location.getFqdn(),
                    status);
            ConfigManagerImpl.fail(m_jobContext, label, job, new ConfigException(msg));
        } else {
            m_jobContext.success(job);
        }
    } catch (Exception e) {
        ConfigManagerImpl.fail(m_jobContext, label, job, e);
    } finally {
        IOUtils.closeQuietly(log);
    }
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java

/**
 * Gives fresh numbers to all nodes in a tree pattern.
 * /*from ww  w. j  a  va  2s.  c  o  m*/
 */
public void renumberNodes() {
    Stack<NavigationTreePatternNode> st = new Stack<NavigationTreePatternNode>();
    st.push(this.root);
    while (!st.empty()) {
        NavigationTreePatternNode pn = st.pop();
        if (pn.getNodeCode() == -1) {
            // nothing
            //Parameters.logger.debug("-1 node! Left unchanged");
        } else {
            pn.setNodeCode(NavigationTreePatternNode.globalNodeCounter.getAndIncrement());
        }
        Iterator<NavigationTreePatternEdge> ie = pn.getEdges().iterator();
        while (ie.hasNext()) {
            st.push(ie.next().n2);
        }
    }
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java

/**
 * Same as {@link #renumberNodes()}, but it starts the numbering from the localCounter.
 * // w w w.j  av  a2s  .  co m
 * @author Konstantinos KARANASOS
 */
public void renumberNodes(int localCounter) {
    Stack<NavigationTreePatternNode> st = new Stack<NavigationTreePatternNode>();
    st.push(this.root);
    while (!st.empty()) {
        NavigationTreePatternNode pn = st.pop();
        if (pn.getNodeCode() == -1) {
            // nothing
            //Parameters.logger.debug("-1 node! Left unchanged");
        } else {
            pn.setNodeCode(localCounter);
            localCounter++;
        }
        Iterator<NavigationTreePatternEdge> ie = pn.getEdges().iterator();
        while (ie.hasNext()) {
            st.push(ie.next().n2);
        }
    }
}

From source file:net.dv8tion.jda.core.entities.impl.MessageImpl.java

@Override
public synchronized String getStrippedContent() {
    if (strippedContent == null) {
        String tmp = getContent();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find()) {
                tokens.add(new FormatToken(key, matcher.start()));
            }//from   w  w w.ja va  2s .  c om
        }

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Stack<FormatToken> stack = new Stack<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.empty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start) {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.empty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.empty()) {
                    //close tag closed the block
                    inBlock = false;
                }
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start) {
                out.append(tmp.substring(currIndex, formatToken.start));
            }
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length()) {
            out.append(tmp.substring(currIndex));
        }
        //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block
        strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
    return strippedContent;
}

From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultTreeView.java

private TreePath getTreePath(TreePath currentPath, ViewState state) {
    String lookingForPath = state.getCurrentMetGroup();
    Stack<DefaultMutableTreeNode> stack = new Stack<DefaultMutableTreeNode>();
    DefaultMutableTreeNode baseNode = (DefaultMutableTreeNode) currentPath.getLastPathComponent();
    for (int i = 0; i < baseNode.getChildCount(); i++) {
        stack.push((DefaultMutableTreeNode) baseNode.getChildAt(i));
    }//from ww  w  .  j av  a  2s  .  c  o  m
    while (!stack.empty()) {
        DefaultMutableTreeNode node = stack.pop();
        if (node.getUserObject().equals("static-metadata")) {
            for (int i = 0; i < node.getChildCount(); i++) {
                stack.push((DefaultMutableTreeNode) node.getChildAt(i));
            }
        } else if (node.getUserObject() instanceof ConcurrentHashMap) {
            String key = (String) ((ConcurrentHashMap<String, String>) node.getUserObject()).keySet().iterator()
                    .next();
            if (lookingForPath.equals(key)) {
                return new TreePath(node.getPath());
            } else if (lookingForPath.startsWith(key + "/")) {
                lookingForPath = lookingForPath.substring(lookingForPath.indexOf("/") + 1);
                stack.clear();
                for (int i = 0; i < node.getChildCount(); i++) {
                    stack.add((DefaultMutableTreeNode) node.getChildAt(i));
                }
            }
        }
    }
    return currentPath;
}

From source file:org.pentaho.platform.engine.services.MessageFormatter.java

public void formatExceptionMessage(String mimeType, ActionSequenceException exception,
        StringBuffer messageBuffer) {
    if ("text/html".equals(mimeType)) { //$NON-NLS-1$
        String templateFile = null;
        String templatePath = "system/ui/templates/viewActionErrorTemplate.html"; //$NON-NLS-1$
        try {/* w  w  w  .  jav  a  2 s .c o m*/
            byte[] bytes = IOUtils
                    .toByteArray(ActionSequenceResource.getInputStream(templatePath, LocaleHelper.getLocale()));
            templateFile = new String(bytes, LocaleHelper.getSystemEncoding());
        } catch (IOException e) {
            messageBuffer.append(Messages.getInstance()
                    .getErrorString("MessageFormatter.RESPONSE_ERROR_HEADING", templatePath)); //$NON-NLS-1$
            e.printStackTrace();
        }

        // NOTE: StringUtils.replace is used here instead of String.replaceAll because since the latter uses regex,
        // the
        // replacment
        // text can cause exceptions if '$' or other special characters are present. We cannot guarantee that the
        // replacement
        // text does not have these characters, so a non-regex replacer was used.

        // TODO: there is a bit of extraneous String object creation here. If performance becomes an issue, there are
        // more
        // efficient
        // ways of doing mass replacements of text, such as using StringBuilder.replace

        // %ERROR_HEADING%
        templateFile = StringUtils.replace(templateFile, "%ERROR_HEADING%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_ERROR_HEADING")); //$NON-NLS-1$

        // %EXCEPTION_MSG%
        templateFile = StringUtils.replace(templateFile, "%EXCEPTION_MSG%", //$NON-NLS-1$
                StringEscapeUtils.escapeHtml(exception.getMessage() == null ? "" : exception.getMessage())); //$NON-NLS-1$
        templateFile = StringUtils.replace(templateFile, "%EXCEPTION_MSG_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_MSG_LABEL")); //$NON-NLS-1$

        // %EXCEPTION_TIME%
        templateFile = StringUtils.replace(templateFile, "%EXCEPTION_TIME%", //$NON-NLS-1$
                StringEscapeUtils.escapeHtml(dateFormat.format(exception.getDate())));
        templateFile = StringUtils.replace(templateFile, "%EXCEPTION_TIME_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_TIME_LABEL")); //$NON-NLS-1$

        // %EXCEPTION_TYPE%
        templateFile = StringUtils.replace(templateFile, "%EXCEPTION_TYPE%", //$NON-NLS-1$
                StringEscapeUtils.escapeHtml(exception.getClass().getSimpleName()));
        templateFile = StringUtils.replace(templateFile, "%EXCEPTION_TYPE_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_TYPE_LABEL")); //$NON-NLS-1$

        // %SESSION_ID%
        templateFile = StringUtils.replace(templateFile, "%SESSION_ID%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$
                .getSessionId() == null ? "" : exception.getSessionId())); //$NON-NLS-1$
        templateFile = StringUtils.replace(templateFile, "%SESSION_ID_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_SESSION_ID_LABEL")); //$NON-NLS-1$

        // %INSTANCE_ID%
        templateFile = StringUtils.replace(templateFile, "%INSTANCE_ID%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$
                .getInstanceId() == null ? "" : exception.getInstanceId())); //$NON-NLS-1$
        templateFile = StringUtils.replace(templateFile, "%INSTANCE_ID_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_INSTANCE_ID_LABEL")); //$NON-NLS-1$

        // %ACTION_SEQUENCE%
        templateFile = StringUtils.replace(templateFile, "%ACTION_SEQUENCE%", //$NON-NLS-1$
                StringEscapeUtils.escapeHtml(exception.getActionSequenceName() == null ? "" : exception.getActionSequenceName())); //$NON-NLS-1$
        templateFile = StringUtils.replace(templateFile, "%ACTION_SEQUENCE_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_ACTION_SEQUENCE_LABEL")); //$NON-NLS-1$

        // %ACTION_SEQUENCE_EXECUTION_STACK%
        CharArrayWriter charWriter = new CharArrayWriter();
        PrintWriter printWriter = new PrintWriter(charWriter);
        exception.printActionExecutionStack(printWriter);
        templateFile = StringUtils.replace(templateFile, "%ACTION_SEQUENCE_EXECUTION_STACK%", //$NON-NLS-1$
                StringEscapeUtils.escapeHtml(charWriter.toString()));
        templateFile = StringUtils.replace(templateFile, "%ACTION_SEQUENCE_EXECUTION_STACK_LABEL%", //$NON-NLS-1$
                Messages.getInstance().getString(
                                "MessageFormatter.RESPONSE_EXCEPTION_ACTION_SEQUENCE_EXECUTION_STACK_LABEL")); //$NON-NLS-1$

        // %ACTION_CLASS%
        templateFile = StringUtils.replace(templateFile, "%ACTION_CLASS%", //$NON-NLS-1$
                StringEscapeUtils.escapeHtml(exception.getActionClass() == null ? "" : exception.getActionClass())); //$NON-NLS-1$
        templateFile = StringUtils.replace(templateFile, "%ACTION_CLASS_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_ACTION_CLASS_LABEL")); //$NON-NLS-1$

        // %ACTION_DESC%
        templateFile = StringUtils.replace(templateFile, "%ACTION_DESC%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$
                .getStepDescription() == null ? "" : exception.getStepDescription())); //$NON-NLS-1$
        templateFile = StringUtils.replace(templateFile, "%ACTION_DESC_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_ACTION_DESC_LABEL")); //$NON-NLS-1$

        // %STEP_NUM%
        templateFile = StringUtils.replace(templateFile, "%STEP_NUM%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$
                .getStepNumber() == null
                        ? Messages.getInstance().getString("MessageFormatter.EXCEPTION_FIELD_NOT_APPLICABLE") //$NON-NLS-1$
                        : exception.getStepNumber().toString()));
        templateFile = StringUtils.replace(templateFile, "%STEP_NUM_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_STEP_NUM_LABEL")); //$NON-NLS-1$

        // %STEP_NUM%
        templateFile = StringUtils.replace(templateFile, "%LOOP_INDEX%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$
                .getLoopIndex() == null
                        ? Messages.getInstance().getString("MessageFormatter.EXCEPTION_FIELD_NOT_APPLICABLE") //$NON-NLS-1$
                        : exception.getLoopIndex().toString()));
        templateFile = StringUtils.replace(templateFile, "%LOOP_INDEX_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_LOOP_INDEX_LABEL")); //$NON-NLS-1$

        // %STACK_TRACE%
        charWriter = new CharArrayWriter();
        printWriter = new PrintWriter(charWriter);
        exception.printStackTrace(printWriter);
        templateFile = StringUtils.replace(templateFile, "%STACK_TRACE%", //$NON-NLS-1$
                StringEscapeUtils.escapeHtml(charWriter.toString()));
        templateFile = StringUtils.replace(templateFile, "%STACK_TRACE_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_STACK_TRACE_LABEL")); //$NON-NLS-1$

        // %EXCEPTION_MESSAGES%
        Stack<String> causes = new Stack<String>();
        buildCauses(causes, exception);
        charWriter = new CharArrayWriter();
        printWriter = new PrintWriter(charWriter);
        while (!causes.empty()) {
            printWriter.println(causes.pop());
        }
        templateFile = StringUtils.replace(templateFile, "%EXCEPTION_MESSAGES%", //$NON-NLS-1$
                StringEscapeUtils.escapeHtml(charWriter.toString()));
        templateFile = StringUtils.replace(templateFile, "%EXCEPTION_MESSAGES_LABEL%", Messages.getInstance() //$NON-NLS-1$
                .getString("MessageFormatter.RESPONSE_EXCEPTION_MESSAGES_LABEL")); //$NON-NLS-1$

        // %SERVER_INFO% (if available)
        if (PentahoSystem.getObjectFactory().objectDefined(IVersionHelper.class.getSimpleName())) {
            IVersionHelper versionHelper = PentahoSystem.get(IVersionHelper.class);
            templateFile = StringUtils.replace(templateFile, "%SERVER_INFO%", Messages.getInstance().getString( //$NON-NLS-1$
                    "MessageFormatter.USER_SERVER_VERSION", //$NON-NLS-1$
                    versionHelper.getVersionInformation(PentahoSystem.class)));
        }

        messageBuffer.append(templateFile);
    }
}