cancel
Showing results for 
Search instead for 
Did you mean: 

call my web script

dmralfing
Champ in-the-making
Champ in-the-making
I have implemented a web script that works OK. It works fine writting this in the browser:
    http://localhost:8080/alfresco/service/demo/readonly/prueba
But I want to call it from a java program. The program is:

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

   public static void test (String hostname, String port, String user, String password) throws Exception
   {
      try
      {
         URL_BASE="http://'+hostname+':'+port;
         DefaultHttpClient client = new DefaultHttpClient();
         HttpPost post = new HttpPost(URL_BASE+"/share/page/dologin");
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
         nameValuePairs.add(new BasicNameValuePair("username", user));
         nameValuePairs.add(new BasicNameValuePair("password", password));
         post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         client.execute(post);
         setCookieStore(client.getCookieStore());
         executeGET (client.getCookieStore(),"http://localhost:8080/alfresco/service/demo/readonly/prueba");
      }
      catch (Exception ex)
      {
         throw new Exception ("No se pudo realizar la conexión al servidor \""+hostname+ "\" por el puerto "+port+" con el usuario y password indicados.");
      }
      
   }//connect
private static String executeGET (CookieStore cookieStore, String url) throws Exception 
   {
      
      System.out.println(url);
      if (cookieStore==null)
           throw new Exception("ERR. Cookie Store NULO");
      String result=null;
        InputStream instream=null;
        try
        {
            DefaultHttpClient client = new DefaultHttpClient();
            client.setCookieStore(cookieStore);
            HttpGet  httpget = new HttpGet(url);
            HttpResponse  response = client.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity==null) throw new Exception("ERROR. El objeto entity es nulo");
                instream = entity.getContent();
                result = IOUtils.toString(instream);
                System.out.println(result);
              
         }//try
         catch (ClientProtocolException ex){ex.printStackTrace();}
         catch (IOException ex){ex.printStackTrace();}
         catch (Exception ex){ex.printStackTrace();}
         finally{ if (instream!=null) instream.close();}
         return result;
   }//execute

Somebody knows what do I´m doing wrong?
8 REPLIES 8

kaynezhang
World-Class Innovator
World-Class Innovator
What is your error?
Following is an example of call GetMethod you can refer to



      HttpClient client = new HttpClient();
      client.getState().setCredentials(
            new AuthScope("localhost", 8080, "Alfresco"),
            new UsernamePasswordCredentials("admin", "admin"));
      String uid = "1565a32e-7863-45af-a9fa-b68ad206b5e7";
      String apiurl = "http://localhost:8080/alfresco/service/api/node/workspace/SpacesStore/'+uid+'/versions";
      GetMethod get = new GetMethod(apiurl);
      try {

         get.setDoAuthentication(true);
         get.setRequestHeader("Content-Type", "application/json");
   

         int status = client.executeMethod(get);
         if (status != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + get.getStatusLine());
         }
         String resultString = get.getResponseBodyAsString();
         System.out.println(resultString);
         
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         get.releaseConnection();
      }

dmralfing
Champ in-the-making
Champ in-the-making
Ok, it works fine doing it with your function. Do you know also how can I adapt the Web Script to let him be called through "/share/proxy"?,
For example: http://localhost:8080//share/proxy/

kaynezhang
World-Class Innovator
World-Class Innovator
I'm sorry ,what do you mean by "adapt the Web Script to let him be called through "/share/proxy""? could you restate it?

dmralfing
Champ in-the-making
Champ in-the-making
For example, if I want to call my web script I have to do:
    "http://localhost:8080/alfresco/service/demo/readonly/prueba"
But I have seen in a lot of examples that you can call the same webscript doing something like this:
      "http://localhost:8080/share/proxy/alfresco/service/demo/readonly/prueba"
   I need it because I´m using a Web Script allocated in my Alfresco that I call since the Share, so if I don´t do it like that, the system force to authenticate again due to the connection to Alfresco since the Share, and I'd rather to avoid it. I guess that if I call the web script with "share/proxy" it won´t be necessary that authentication..

kaynezhang
World-Class Innovator
World-Class Innovator
If you are calling alfresco web script api  from share using script js , you can use remote object.
If you are calling alfresco web script api from share usring java ,you can use ScriptRemote

        ScriptRemote scriptRemote = serviceRegistry.getScriptRemote();
        Response response = scriptRemote.connect().get(uri);

dmralfing
Champ in-the-making
Champ in-the-making
The problem is that I use Ajax in my Share to load data values in some combos.
Being queries, Alfresco repository must be acceses so  it makes me authenticate again,
and what I want is to avoid it.
Wathing my code you will understand better, it is:



var urlService3= window.location.protocol + '//' + window.location.host + '/alfresco/service/com/portales/intranet/combos/tipos/listado';
 
    $.ajax({
        type: "GET",
        url: urlService3,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response3) {
            var results3 = response3;
                                               $( "select[name='prop_prtls_tipo_documento']" ).html("");
            for(var i=0;i<results3.length;i++){
                                                              
                                                               $( "select[name='prop_prtls_tipo_documento']" ).append("<option value='"+results3.valor+"'>"+results3.valor+"</option>");
                                               }                                            
        },
        error: function(xhr, status, error) {
            var errorMessage = error.description != null ? error.description : error;
                                              
                                               $( "select[name='prop_prtls_tipo_documento']" ).html("<option value='"+errorMessage+"'>"+urlService3+"_"+errorMessage+"</option>");
        }
    });

kaynezhang
World-Class Innovator
World-Class Innovator
You can call Alfresco webscript api using client-side javascript from share like below code :

Alfresco.util.Ajax.request(
{
   url: Alfresco.constants.PROXY_URI + urlService3,
   method: Alfresco.util.Ajax.GET (if you want to use post method ,please use  Alfresco.util.Ajax.POST)
   dataObj:
   {   
                data1: "data1",
                submitType: "json"
   },
   successCallback:
   {
      fn: this.success, // success callback method
      scope: this
   },
   failureCallback:
   {
      fn: this.failure, // failure callback method
      scope: this
   }
});

romschn
Star Collaborator
Star Collaborator
Can you try making ajax call using Alfresco.util.Ajax.request? Also, if you are already logged into alfresco share and invoking repository webscripts then it should not again ask for authentication.