Maven
The first step is to add Jackson dependency in the maven configuration. Add in the module configuration file:
35 <dependency> 36 <groupId>org.codehaus.jackson</groupId> 37 <artifactId>jackson-mapper-asl</artifactId> 38 <version>1.8.5</version> 39 </dependency>
URLConnectionReader
In order to simplify the template. A class URLConnectionReader has been created which provides only one function:
24 interface URLConnectionReader { 25 String getContent(URL url) throws IOException; 26 }The function receives an URL and returns the content as a string
URLConnectionReaderImpl
The implementation of the interface is the following:28 public class URLConnectionReaderImpl implements URLConnectionReader { 29 30 public String getContent(URL url) throws IOException { 31 StringBuilder buffer = new StringBuilder(); 32 URLConnection yc = url.openConnection(); 33 34 BufferedReader in = new BufferedReader(new InputStreamReader( 35 yc.getInputStream(), Charset.defaultCharset())); 36 String inputLine; 37 while ((inputLine = in.readLine()) != null) 38 buffer.append(inputLine); 39 in.close(); 40 return buffer.toString(); 41 } 42 43 }Now, that we have this class ready, it becomes easy to implement the YoctoTemplate
StandaloneYoctoTemplate
For simplicity's sake, I will only show the main functions:Synchronous query
46 47 public YoctoMap query(String relativePath) { 48 ObjectMapper mapper = new ObjectMapper(); 49 try { 50 URL newUrl = new URL(url, relativePath); 51 String content = reader.getContent(newUrl); 52 if (content == null) throw new IllegalStateException("Content is empty"); 53 return new StandaloneYoctoMap((Map<String, Object>) mapper.readValue(content, Map.class)); 54 } catch (IOException e) { 55 throw new RuntimeException(e); 56 } 57 }
Basically, the function:
- calls the reader
- receives a string
- parses the string using Jackson's ObjectMapper.
- Returns the result in a YoctoMap object
The result will then be analyzed by the YoctoObjectImpl...
Asynchronous query
The asynchronous query will use a thread to call the reader in background, here is the implementation of the function:
54 55 public void aSyncQuery(String relativePath, YoctoCallback<YoctoMap> listener) { 56 Thread thread = new Thread(new BackgroundQuerier(relativePath, listener)); 57 thread.start(); 58 } 59 60 private class BackgroundQuerier implements Runnable { 61 62 private YoctoCallback<YoctoMap> listener; 63 private String relativePath; 64 65 public BackgroundQuerier(String relativePath, YoctoCallback<YoctoMap> listener) { 66 this.relativePath = relativePath; 67 this.listener = listener; 68 } 69 70 public void run() { 71 YoctoMap result; 72 try { 73 result = query(relativePath); 74 } catch (Throwable t) { 75 listener.onError(t); 76 return; 77 } 78 listener.onSuccess(result); 79 } 80 }