0

I have a mule program that I want to read a file from my PC and display the content in the browser on localhost.

I have it working for one file hard coded as seen below.

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) {


     message.setPayload(outputEncoding);
    return null;

}

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;
}

}

How can i specify it to read any file I input through the URL and not just my hard coded file?

Matt
  • 14,906
  • 27
  • 99
  • 149
gio10245
  • 37
  • 2
  • 13

3 Answers3

0

You could use the HttpServer class for this. You application will listen HTTP requests. Therefore, you can put the following URL in your browser:

"localhost/file_to_be_loaded"

Your HttpServer will receive a GET request for URL (localhost/file_to_be_loaded)

Parse the request, load the file and respond to the browser.

It may seem complex, but is very simple. The first answer in the post below does almost all the job:

simple HTTP server in Java using only Java SE API

Good luck!

Community
  • 1
  • 1
  • I already have a server in Mule through localhost so I'm not sure if I need another one? – gio10245 Oct 05 '15 at 12:45
  • You should take a look at this to see how you can get the request path, query params, etc: https://docs.mulesoft.com/mule-user-guide/v/3.7/http-listener-connector#mapping-between-http-requests-and-mule-messages. With that you should be able to take the filename from the HTTP request. HTH. – afelisatti Oct 05 '15 at 12:54
  • The parameters will be present in the message most likely as inbound properties. – afelisatti Oct 05 '15 at 13:38
0

To achieve this you need to use Mule expression language. Follow below steps

1) use below session component after HTTP. This will store the filePath coming from your HTTP url in a session variable.

 <set-session-variable variableName="Filepath" value="#[message.inboundProperties.'http.query.params'.Filepath]" doc:name="Session Variable"/>

2) In your java code, read the session variable using below line of code. Then pass the filepath to your method insted of hardcoding

 String filePath = eventContext.getMessage().getProperty("Filepath", PropertyScope.SESSION);

3) Finally trigger the service some thing like below HTTP url with query param

http://localhost:8083/?Filepath=C:\\test.txt

I suggest, go through the mule documentation for Mule expression language. That will give more clarity on how to work this type of scenarios.

RamakrishnaN
  • 367
  • 3
  • 9
  • Sorry forgot tell you.I did in different way. Its almost similar to your code. Now in your case do like this for the Filepath to pass 1) get the Filepath in your transformMessage method, like String filePath = message.getProperty("Filepath", PropertyScope.SESSION); 2) Then pass the string Filepath to methods getFileName and readFile. 3) Finally replace the hard code value with String filePath in both this methods. Hope this will work for you. – RamakrishnaN Oct 05 '15 at 14:59
  • Ok let me post my code that I have tried and tested. – RamakrishnaN Oct 05 '15 at 15:17
0

My Xml code

 <flow name="filetestFlow1">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
    <logger message="--- Service triggred --" level="INFO" doc:name="Logger"/>
    <set-session-variable variableName="Filepath" value="#[message.inboundProperties.'http.query.params'.Filepath]" doc:name="Session Variable"/>
    <component class="filetest.ReadFile" doc:name="Java"/>
</flow>

Java code, Here you can observe that I implemented Callable interface

public class ReadFile implements Callable {

@Override
public Object onCall(MuleEventContext eventContext) throws Exception {
    // TODO Auto-generated method stub
    System.out.println("Service triggred in java");
    String filePath = eventContext.getMessage().getProperty("Filepath", PropertyScope.SESSION);
    MuleMessage msg = eventContext.getMessage();
    String filename = getFileName(msg,filePath);
    String content = readFile(filename,filePath);
    setPayload(msg, content);
    return msg;

}

/**
 * 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,String filePath) {
    File file;
    file = new File(filePath);
    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,String filePath) {

    Path p = Paths.get(filePath);
    String file = p.getFileName().toString();
    return file;

}

public String setPayload(MuleMessage message, String outputEncoding) {

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

}

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

}

RamakrishnaN
  • 367
  • 3
  • 9
  • This fails to deploy for me – gio10245 Oct 05 '15 at 15:29
  • Actually i got it to work now, thanks very much for your help – gio10245 Oct 05 '15 at 15:42
  • Good to see it's working. FYI, further you can refine the code. Currently we stored the URL query parameter "Filepath" value in a session variable then we retrieved from Java code. Instead we can directly fetch the HTTP query parameter value in java code (in onCall method) like ----- ParameterMap map = eventContext.getMessage().getInboundProperty( "http.query.params"); String filePath = map.get("Filepath"); – RamakrishnaN Oct 05 '15 at 17:14
  • Can I suggest to create a new question with details on what you need. Otherwise it will be difficult for others to track this. – RamakrishnaN Oct 06 '15 at 08:44