cancel
Showing results for 
Search instead for 
Did you mean: 

Does WebScript provide callback?

dynamolalit
Champ on-the-rise
Champ on-the-rise
Hi,

I have written a webscript which gives me a string as result. Now i want to show it on my custom dashlet.

For this does Alfresco provides any kind of callback methods for webscripts so that result of webscript execution can be accessed via these methods & manipulated.  :?:

Its urgent.
5 REPLIES 5

stevegreenbaum
Champ in-the-making
Champ in-the-making
The way I do this is by returning json from my web script.  In the dashlet controller you can call your web script and generate the html for display in the dashlet.  Here is an example of an OOTB dashlet controller (site-links):

function sortByTitle(link1, link2)
{
   return (link1.title > link2.title) ? 1 : (link1.title < link2.title) ? -1 : 0;
}

function main()
{
   var site, container, theUrl, connector, result, links;
  
   site = page.url.templateArgs.site;
   container = 'links';
   theUrl = '/api/links/site/' + site + '/' + container + '?page=1&pageSize=512';
   connector = remote.connect("alfresco");
   result = connector.get(theUrl);
   if (result.status == 200)
   {
      links = eval('(' + result.response + ')').items;
      links.sort(sortByTitle);
      model.links = links;
      model.numLinks = links.length;
     model.tags=links.tags;
   }
}

main();

dynamolalit
Champ on-the-rise
Champ on-the-rise
Hi SteveGreenbaum ,

Thanks for your quick reply.I am trying to invoke a Java backed web script from dashlet as soon as user logs in & render the results to user in dashlet which is no of documents uploaded by him. I am able to get output till dashlet JSP but it is not getting rendered on dashlet in Explorer & no output is shown in dashlet & it is showing blank. :!:

Here is my source:

Dashlet Jsp(userStatistics.jsp):


<%@ taglib uri="/WEB-INF/repo.tld" prefix="r" %>
<%@ page import="com.xxxx.alfresco.km.webscripts.WebScriptInvoker"%>
<%@ page import="com.xxxx.alfresco.km.webscripts.WebScriptCall"%>

Total Number of content for You is :
<%
System.out.println("Calling WebScriptCall in JSP");
WebScriptCall webScriptCall = new WebScriptCall();
String temp = webScriptCall.getOutput();
System.out.println("Web Script output in JSP "+temp);
%>

Total Number of content for You is : <%=temp%>

WebScriptCall .java:

public class WebScriptCall {

   List<String> temp = new ArrayList<String>();
   public String getOutput(){
      System.out.println("Invoking web script in WebScriptCall");
      WebScriptInvoker invoker = new WebScriptInvoker();
      String userName = "admin";
      String password = "admin";
      String method = "GET";
      String webScriptUrl = "http://localhost:8080/alfresco/service/com/xxxx/alfresco/km/getuserstatistics?userName=admin&format=...";
      System.out.println("Inside WebScriptCall : userName "+userName+" password "+password+" method "+method+" scriptURL "+webScriptUrl);
      String result = invoker.doWork(userName , password , method , webScriptUrl);
      System.out.println("result in  WebScriptCall "+result);
      return result;
   }
   
}

WebScriptInvoker .java :


public String doWork(String userName, String password, String method, String webScriptURL) {
      logger.debug("Inside doWork : userName "+userName+" password "+password+" method "+method+" scriptURL "+webScriptURL);
      String result;
      //WebScriptInvoker invoker = new WebScriptInvoker();
       setUser(userName);
       setPassword(password);
       setMethod(method);
       setScriptUrl(webScriptURL);       
       //logger.debug("userName "+getUser()+" password "+getPassword()+" method "+getMethod()+" scriptURL "+getScriptUrl());
       
      HttpURLConnection conn = null;
      
      try {
         
         //logger.debug("1");
         AuthenticationUtils.startSession(getUser(), getPassword());
         //logger.debug("2");
         setTicket(AuthenticationUtils.getTicket());
         //logger.debug("3");
         URL scriptUrl = (new URI(getScriptUrl())).toURL();
         //logger.debug("4");
         logger.debug("Invoking Web Script : " + scriptUrl);
         
         conn = (HttpURLConnection)scriptUrl.openConnection();
         //logger.debug("5");
         conn.setRequestMethod(getMethod());
         //logger.debug("6");
         conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBytes((getTicket()).getBytes()));
         //logger.debug("7");
         //3.0 and later can do HTTP method tunneling
         //conn.setRequestProperty("X-HTTP-Method-Override", "POST");
         conn.connect();         
                  
         logger.debug("Response code: " + conn.getResponseCode());
         
         BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));   
         //logger.debug("8");
         StringBuffer buffer = new StringBuffer();
         //logger.debug("9");
         String line;
         while ((line = in.readLine()) != null) {
            //logger.debug("line "+line);
            buffer.append(line);
            //logger.debug("buffer in doWork() "+buffer.toString());
         }
         logger.debug("Web Script Output in doWork() "+buffer.toString());
         result = buffer.toString();
         //logger.debug("11");
      } catch (Exception serviceException) {
         logger.error("Exception while invoking web script "+serviceException.getMessage());
           throw new RuntimeException("Problem invoking web script", serviceException);
       } finally {           
           // End the session
           AuthenticationUtils.endSession();
           if (conn != null) conn.disconnect();
       }
      // logger.debug("12");
       return result;
   }
   

GetUserStatisticsWebScript.java:


public void execute(WebScriptRequest req, WebScriptResponse res)
         throws IOException {
      int totalNoOfContent = 0;
      int approvedContent = 0;
      int rejectedContent = 0;
      int underReviewContent = 0;
      String userName = req.getParameter("userName");
      logger.debug("User name to get statistics is " + userName);
      nodeService = serviceRegistry.getNodeService();
   //   setAuthenticationService(serviceRegistry.getAuthenticationService());
      StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE,
            "SpacesStore");
      SearchParameters sp = new SearchParameters();
      sp.addStore(storeRef);
      sp.setLanguage(SearchService.LANGUAGE_LUCENE);
      sp.setQuery("@cm\\:originalOwner:" + userName + "");
      //sp.setQuery("TYPE:\"{http://www.alfresco.org/model/content/1.0}person\"");
      ResultSet results = null;
      try {
         results = getSearchService().query(sp);
         logger.debug("Size of resultset is " + results.length());
         totalNoOfContent = results.length();
         for (ResultSetRow row : results) {
            NodeRef currentNodeRef = row.getNodeRef();
            // logger.debug("currentNodeRef "+currentNodeRef);
            QName statusQname = QName
                  .createQName("{http://www.alfresco.org/model/content/1.0}contentStatus");
            nodeService.getProperty(currentNodeRef, statusQname);
            logger.debug("Status for "
                  + currentNodeRef.toString()
                  + " is "
                  + nodeService.getProperty(currentNodeRef, statusQname)
                        .toString());
            if((nodeService.getProperty(currentNodeRef, statusQname)
                  .toString()).equalsIgnoreCase("underreview")){
               underReviewContent = underReviewContent + 1;
            }else if ((nodeService.getProperty(currentNodeRef, statusQname)
                  .toString()).equalsIgnoreCase("approved")) {
               approvedContent = approvedContent + 1;
            } else if ((nodeService
                  .getProperty(currentNodeRef, statusQname).toString())
                  .equalsIgnoreCase("rejected")) {
               rejectedContent = rejectedContent + 1;
            }
         }
         logger.debug("totalNoOfContent " + totalNoOfContent);
         logger.debug("approvedContent " + approvedContent);
         logger.debug("rejectedContent " + rejectedContent);
         // Now for each of these getthe status.
         
         result = new HashMap<String, String>();
         Integer tempTotalCount = new Integer(totalNoOfContent);
         result.put("totalNoOfContent", tempTotalCount.toString());
         Integer tempAppCount = new Integer(approvedContent);
         result.put("approvedContent", tempAppCount.toString());
         Integer tempRejCount = new Integer(rejectedContent);
         result.put("rejectedContent", tempRejCount.toString());
         logger.debug("totalNoOfContent  "+tempTotalCount.toString()+"  approvedContent "+tempAppCount.toString()+ "  rejectedContent " + tempRejCount.toString());
         String finalOutput = "";
         finalOutput += tempTotalCount.toString();
         //finalOutput.concat(tempTotalCount.toString());
         finalOutput+=":";
         finalOutput+= tempAppCount.toString();
         finalOutput+=":";
         finalOutput+= tempRejCount.toString();
         logger.debug("Calling output method in web script");
         output(res, finalOutput);
      } finally {
         if (results != null) {
            totalNoOfContent = 0;
            approvedContent = 0;
            rejectedContent = 0;
            underReviewContent = 0;
            results.close();
         }
      }
      //return result;
   }
   
   protected void output(WebScriptResponse res,String result) {
      logger.debug("Passing back the output " + result);
      try {
         res.setContentType("text/html");
         res.getOutputStream().write(result.getBytes());
         //logger.debug("Output in output() :- " + res.getOutputStream());         
      } catch (Exception e) {
         throw new WebScriptException("Unable to stream output");
      }      
      finally{
         if(res!=null){
            try {
               if(res.getOutputStream()!=null){
                  res.getOutputStream().close();
               }
            } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }         
         }
      }
   }

Finally the logs:


Calling WebScriptCall in JSP
Invoking web script in WebScriptCall
Inside WebScriptCall : userName admin password admin method GET scriptURL http://localhost:8080/alfresco/service/com/xxxx/alfresco/km/getuserstatistics?userName=admin&format=...
09:32:39,208 User:adminDEBUG [km.webscripts.WebScriptInvoker] Inside doWork : userName admin password admin meth
od GET scriptURL http://localhost:8080/alfresco/service/com/xxxx/alfresco/km/getuserstatistics?userName=admin&format=...
09:32:39,239 User:xxxxadmin DEBUG [km.webscripts.WebScriptInvoker] Invoking Web Script : http://localhost:8080/alfresco/service/
com/xxxx/alfresco/km/getuserstatistics?userName=xxxxadmin&format=html
09:32:39,255 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] User name to get statistics is admin
09:32:39,317 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Size of resultset is 7
09:32:39,333 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Status for workspace://SpacesStore/26e4ab1a-6cc6-4b
8f-938c-eff5361fd6c8 is Approved
09:32:39,333 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Status for workspace://SpacesStore/8f75c021-7b1e-46
13-8abc-247e7b4adfd0 is Rejected
09:32:39,333 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Status for workspace://SpacesStore/96a0e9d4-09c7-4c
e0-831c-654457c6ecde is Approved
09:32:39,349 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Status for workspace://SpacesStore/e4224970-d2a4-41
d4-828b-b9880ff62d1a is Rejected
09:32:39,349 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Status for workspace://SpacesStore/71bd05a6-972c-45
f2-9be6-cf24c6cd3f60 is Rejected
09:32:39,364 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Status for workspace://SpacesStore/accc306f-670d-4d
3e-9c35-5479e0acc934 is Rejected
09:32:39,364 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Status for workspace://SpacesStore/339ccba8-e24a-46
ac-8b27-4b4eb3b5198c is Approved
09:32:39,364 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] totalNoOfContent 7
09:32:39,364 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] approvedContent 3
09:32:39,364 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] rejectedContent 4
09:32:39,364 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] totalNoOfContent  7  approvedContent 3  rejectedCon
tent 4
09:32:39,364 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Calling output method in web script
09:32:39,364 User:admin DEBUG [km.webscripts.GetUserStatisticsWebScript] Passing bak the output 7:3:4
09:32:39,364 User:admin DEBUG [km.webscripts.WebScriptInvoker] Response code: 200
09:32:39,380 User:admin DEBUG [km.webscripts.WebScriptInvoker] Web Script Output in doWork() 7:3:4
result in  WebScriptCall 7:3:4
Web Script output in JSP 7:3:4

Everything seems to be in place still no clue. :roll:

dynamolalit
Champ on-the-rise
Champ on-the-rise
Hi Again,

I got the output rendered on dashlet using JSON in my webscript.  Smiley Very Happy

userStatistics.jsp:



<%@ taglib uri="/WEB-INF/repo.tld" prefix="r" %>
<%@ page import="com.xxxx.alfresco.km.webscripts.WebScriptInvoker"%>
<%@ page import="com.xxxx.alfresco.km.webscripts.WebScriptCall"%>
<r:webScript scriptUrl="/wcservice/com/xxxx/alfresco/km/getuserstatistics?userName=#{ NavigationBean.currentUser.userName}" />


Here is the GetUserStatisticsWebScript.java snippet:


public void execute(WebScriptRequest req, WebScriptResponse res)
         throws IOException {

JSONObject obj = new JSONObject();
obj.put("Total Content Uploaded ",tempTotalCount.toString());
obj.put("Approved Content ",tempAppCount.toString());
obj.put("Rejected Content ",tempRejCount.toString());
String jsonString = obj.toString();
String finalOutput = "";
finalOutput += "Total Content ";
finalOutput += obj.getString("Total Content Uploaded ");
finalOutput += "\\n";
finalOutput += "Approved Content ";
finalOutput += obj.getString("Approved Content ");
finalOutput += "\\n";
finalOutput += "Rejected Content ";
finalOutput += obj.getString("Rejected Content ");
logger.debug(" finalOutput "+finalOutput);
res.getWriter().write(finalOutput);

}

So far so good!

But newline is not getting displayed & output is rendered like :

Total Content 7\nApproved Content 3\nRejected Content 4

If I user "\n" instaed of  "\\n", then output is something like this:

Total Content 7 Approved Content 3 Rejected Content 4

But still not a new line.

Also i want to know if Alfresco supports only JSON callback or HTML & other formats also?

Any idea! :idea:

stevegreenbaum
Champ in-the-making
Champ in-the-making
Glad you've made some progress.  I see there was a disconnect regarding your original question.  I assumed you were asking about dashlets in Alfresco Share.  I think you are actually referring to dashlets in the Alfresco client. The code snippet I provided was appropriate to Share. 

Check out the HTTP Response Formats section of this page to see all of the supported response formats:  http://wiki.alfresco.com/wiki/Web_Scripts_Framework

dynamolalit
Champ on-the-rise
Champ on-the-rise
Hi,

Thanks a lot for help.

res.setContentType("text/html ");

did the trick. Smiley Happy

P.S. :- I am implementing custom dashlet in Alfresco Explorer.