0
votes

I am trying to create a simple mule application that reads the name and content of a file on the disk and displays it on the web browser.

My flow is as follows HTTP -> JAVA TRANSFORMER - SETPAYLOAD - HTTP

My Java transformer code includes the following

public class ReadFile extends AbstractMessageTransformer {

    /**
     * loads the content of the file specified in the parameter
     * 
     * @param filename
     *            the name of the file
     * @return the content of the file
     */
    public String readFile(String filename) {
        File file;
        file = new File("O:\\test.txt");
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = reader.readLine()) != null)
                builder.append(line);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuietly(reader);
        }
        return builder.toString();
    }

    public String getFileName(MuleMessage message) {

        Path p = Paths.get("O:\\Test.txt");
        String file = p.getFileName().toString();
        return file;

    }

    public String setPayload(MuleMessage message, String outputEncoding) {

        String payload1 = "#[ReadFile]";
        return payload1;

    }

    private void closeQuietly(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException ignored) {
            }
        }
    }

    @Override
    public Object transformMessage(MuleMessage message, String outputEncoding)
            throws TransformerException {
        String filename = getFileName(message);
        String content = readFile(filename);
        setPayload(message, content);
        return message;
    }

}

I am getting the error Execution of the expression ReadFile failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: String

and have no idea why?

1

1 Answers

0
votes

Your doing small mistake in your method setPayload. there your not adding file content to MuleMessage. Do like below it will work

public String setPayload(MuleMessage message, String outputEncoding) {

    message.setPayload(outputEncoding);
    //String payload1 = "#[ReadFile]";
    return null;

}

and my flow looks like below (Where I have implemented onCallable method)

 <flow name="filetestFlow1">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
    <logger message="--- Service triggred --" level="INFO" doc:name="Logger"/>
    <component class="filetest.ReadFile" doc:name="Java"/>
</flow>