Using Watson Translation service in an Eclipse SWT application Part 2

The next follow-up to the last article is the code I used to communicate with the Watson Translation service. But first I want to show the flow of the data:

So basically the SWT client sends a JSON string to the server in the body of the message. You can do this as long as you specify application/json as the Content-Type. For JSON, I use the JSON library for Java over at json.org and its been perfect. I have even begun using this library for all of my in memory objects because then I can easily serialize it out for storage or over the network.

Below you will see the primary code to send this message:

JSONObject payload = new JSONObject();
                	
payload.put("toLang", obj.get("to"));
payload.put("text", obj.get("text"));
                	                	
URL url = new URL(pet_bluemix_translation_service);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(payload.toString());
out.close();
                         
//Now get the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                	
String n = in.readLine();
StringBuffer sbValue = new StringBuffer();
                	
while(n != null){
	sbValue.append(n);
	n = in.readLine();
}
in.close();
                	
final String value = sbValue.toString();
Advertisements

Best site for online file (XML, JSON, HTML, SQL) formatting

Screen Shot 2014-04-21 at 9.57.15 AM

Do you ever need to format some encrypted, auto-generated XML, HTML, or JSON? Well, I do this a lot to debug compressed JSON, HTML, and XML files and I found this great site that not only does formatting for some basic file types but also does a heck of a lot more. Some great things FreeFormatter.com does:

  • Formats files with different indents
  • Validators
  • Encoders/Decoders
  • Minifiers
  • Converters
  • Cryptography
  • String escapers

Check it out and let me know what you think!

http://www.freeformatter.com/

 

Classes and Dojo are very cool

Tonight I am looking for a way to make different presentation styles in the attachment viewer.  I figure I would look into making the different presentations with JavaScript classes and with a little bit of inheritance to boot.   Unfortunately JavaScript does not support classes very well and there are a thousand ways to accomplish this, just Google it and you will see.  I of course chose Dojo to get this done because it was dead simple!

I want to have three presentation styles to start – film strip (default), thumbnails, and slide-show.

The main reason  I wanted to have this be like a class hierarchy is because the title part (where it is File: filename) needs to be re-used and eventually I will have common actions under the title like “open“, “save“, “share“.  So I need a base method in a shared class that can be inherited by the subclasses.  Using dojo.declare, the base class is the following:

dojo.declare("showStyle", null, {
 showHeader : function(id){
 },
 showAttachment : function(id, att, idx){
 },
 showTitle : function(id, att){
     var title = document.createElement("div");
     title.innerHTML = "<b>File:</b> <i>" + att.name + "</i><br>    ";
     title.innerHTML += "<small><a href="#" onclick="openAttachment('" + att.file_url + "');return true;" title="Open this file">open</a></small> ";
     title.innerHTML += "<small><a href="#" onclick="viewAttachment('" + att.content_url + "');return true;" title="View this file">view</a></small> ";
     title.innerHTML += "<small><a href="#" onclick="viewAttachment('http://www.facebook.com/sharer.php?u=" + att.content_url + "');return true;" title="Share this file on Facebook">share</a>";
     title.innerHTML += "</small><br><hr>";                  

     dojo.byId(id).appendChild(title);
 },
 showFooter : function(id){
 }
});

Pretty basic right?  The two parameters in showtitle() are the DOM id the HTML will be inserted into and the “att” is the attachment JSON object. The other methods are stubbed out but I could have default implementations of them in the future.

Now for a subclass!   I won’t go into the details but each subclass will implement a showHeader(), showAttachment(), showFooter() and will be called by the framework.  Here is the reworked original code and put into the “filmStrip” subclass.   Notice the statement in red below.  This tells JavaScript to call the showTitle() method which is implemented in the base class.

dojo.declare("filmStrip", showStyle, {    
    showAttachment : function(id, att, idx){
    var codeArea = document.getElementById("code");    

    this.showTitle(id, att);

    if (att.content_url != null && att.content_url.length > 0){

        var node = document.createElement("div");
        node.setAttribute('id','attachment_' + idx);
        node.setAttribute('class','attachment');

        node.appendChild(document.createElement("hr"));
        document.getElementById(id).appendChild(node);

        var xhrArgs = {
            id : 'attachment_' + idx,
            type : att.type,
            preview_url : att.preview_url,
            url : att.content_url,
            handleAs : "text",
            preventCache: true,
            content: {
            id: 'attachment_' + idx
       },

        load : function(response, args){
           document.getElementById(this.id).innerHTML = response;

           var func = getScript(this.type);

           if (func != null)
               func(this.id, this.preview_url);
           }    
        };

     dojo.xhrGet(xhrArgs);

 }else{
     if (statusArea != null)
         statusArea.innerHTML = "<br>Item not recognized: " + att.name;            
     }

 }
});

The end result is, because of inheritance, the code just processes the object like its a base “showStyle” object.

var style = null;

if (_showStyle == 1)
      style = new slideShow();
else (_showStyle == 2)
      style = new tileSyle();
else
      style = new filmStrip();

if (style.showHeader){
      style.showHeader('attachmentArea');
}
 for (var a = 0; a < attachments.length; a++) {
      var att = attachments[a];
      if (att.type && att.type == "attachment"){
           style.showAttachment('attachmentArea', att.data, a);
      }
 }
 if (style.showFooter){
      style.showFooter('attachmentArea');
 }