Search code examples
configurationmuleanypoint-studio

Mulesoft - Load a JSON or XML properties file into a global variable


I am trying to load a relatively simple configuration file into a variable that I can access globally within via MEL. I don't want to use a typical properties field because my structure is not flat.

I was able to get somewhat close by loading the file as a bean as follows, but this left me with a giant string, rather than a hashmap (I can see why, I just didn't know how to fix it):

    <spring:bean id="ClientConfiguration" name="ClientConfiguration" class="java.lang.String" scope="singleton">
        <spring:constructor-arg>
            <spring:bean id="Test" name="org.springframework.util.FileCopyUtils" class="org.springframework.util.FileCopyUtils" factory-method="copyToByteArray">
                <spring:constructor-arg type="java.io.InputStream" value="classpath:client-configuration.json"/>
            </spring:bean>
        </spring:constructor-arg>
    </spring:bean>

Thoughts on appropriate or better ways to do this?


Solution

  • Here is the solution.

    Class file:

    package com.example;
    
    import java.io.File;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.type.TypeReference;
    
    
    public class JSONUtil {
    
        File in;
        public File getIn() {
            return in;
        }
        public void setIn(File in) {
            this.in = in;
        }
    
        public Map<String, Object> getConfigAsMap(){        
            try{
                ObjectMapper mapper = new ObjectMapper();
                TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
    
                Map<String, Object> map = mapper.readValue( in, typeRef);
                System.out.println(map);
                return map;
            } catch(Exception exception){
                exception.printStackTrace();
                return null;
            }
        }
    }
    

    Config:

        <spring:bean id="JSONUtil" class="com.example.JSONUtil" >
                  <spring:property name="in"  value="classpath:client-configuration.json"/>
        </spring:bean>
    
        <spring:bean name="ClientConfiguration" factory-bean="JSONUtil" factory-method="getConfigAsMap" />
    

    This is working and JSON Config is loaded as a Map.