cancel
Showing results for 
Search instead for 
Did you mean: 

Create a site using Alfresco API

sans
Champ in-the-making
Champ in-the-making
Hi,
I want to write java code to create a site using Alfresco API. Any idea how can i do that? What are the steps involved in creating that.
I am able to write create a user using SDK WebServiceSamples. Similarly I want to write a code to create a site.
Any Help appreciated!!

Thanks
sans
14 REPLIES 14

sans
Champ in-the-making
Champ in-the-making
I am able to create a site through the following code.

public class AlfrescoCreateSite //extends BaseAlfrescoSpringTest
{
    private static final String TEST_SITE_PRESET = "testSitePreset";
    //private static final String TEST_SITE_PRESET_2 = "testSitePreset2";
    private static final String TEST_TITLE = "This is my title";
    private static final String TEST_DESCRIPTION = "This is my description";
   
    private SiteService siteService;   
    private ScriptService scriptService;
    private NodeService nodeService;
    private AuthenticationComponent authenticationComponent;
    private TaggingService taggingService;
    private PersonService personService;
    private AuthorityService authorityService;
    private FileFolderService fileFolderService;
    private PermissionService permissionService;
    private ApplicationContext applicationContext;
    private AuthenticationService authenticationService;
    private char[] pass = {'a','d','m','i','n'};
    public static void main(String[] args) throws Exception {
        AlfrescoCreateSite obj = new AlfrescoCreateSite();
        obj.onSetUpInTransaction();
        obj.testCreateSite();
      }
    protected void onSetUpInTransaction() throws Exception
    {
        // Get the required services
        applicationContext = ApplicationContextHelper.getApplicationContext();
        siteService = (SiteService)this.applicationContext.getBean("SiteService");
        scriptService = (ScriptService)this.applicationContext.getBean("ScriptService");
        nodeService = (NodeService)this.applicationContext.getBean("NodeService");
        authenticationService = (AuthenticationService)this.applicationContext.getBean("AuthenticationService");
        authenticationComponent = (AuthenticationComponent)this.applicationContext.getBean("authenticationComponent");
        taggingService = (TaggingService)this.applicationContext.getBean("TaggingService");
        personService = (PersonService)this.applicationContext.getBean("PersonService");
        authorityService = (AuthorityService)this.applicationContext.getBean("AuthorityService");
        fileFolderService = (FileFolderService)this.applicationContext.getBean("FileFolderService");
        permissionService = (PermissionService)this.applicationContext.getBean("PermissionService");
       
        authenticationService.authenticate("admin", pass);
        // Set the current authentication
        //this.authenticationComponent.setCurrentUser(USER_ONE);
    }
    public void testCreateSite()
    {
     // Create a public site
        SiteInfo siteInfo = siteService.createSite(TEST_SITE_PRESET, "mySiteTest", TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PUBLIC);
        checkSiteInfo(siteInfo, TEST_SITE_PRESET, "mySiteTest", TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PUBLIC);    
    }
    private void checkSiteInfo(SiteInfo siteInfo,
            String expectedSitePreset,
            String expectedShortName,
            String expectedTitle,
            String expectedDescription,
            SiteVisibility expectedVisibility)
    {
        junit.framework.Assert.assertNotNull(siteInfo);
        junit.framework.Assert.assertEquals(expectedSitePreset, siteInfo.getSitePreset());
        junit.framework.Assert.assertEquals(expectedShortName, siteInfo.getShortName());
        junit.framework.Assert.assertEquals(expectedTitle, siteInfo.getTitle());
        junit.framework.Assert.assertEquals(expectedDescription, siteInfo.getDescription());
        junit.framework.Assert.assertEquals(expectedVisibility, siteInfo.getVisibility());
        junit.framework.Assert.assertNotNull(siteInfo.getNodeRef());
       
        // Check that the site is a tag scope
        junit.framework.Assert.assertTrue(this.taggingService.isTagScope(siteInfo.getNodeRef()));
    }
}
But when I am trying to access mySite I am getting an exception.
22-Nov-2010 18:27:59 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Spring Surf Dispatcher Servlet threw exception
javax.servlet.ServletException: Could not resolve view with name 'site/mySiteTest/dashboard' in servlet with name 'Spring Surf Dispatcher Servlet'
   at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1042)
   at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
   at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
   at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
   at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.alfresco.web.site.servlet.MTAuthenticationFilter.doFilter(MTAuthenticationFilter.java:74)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.alfresco.web.site.servlet.SSOAuthenticationFilter.doFilter(SSOAuthenticationFilter.java:301)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
   at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
   at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
   at java.lang.Thread.run(Unknown Source)
Any help would be appreciated.

Thanks
Sans!!!

mrogers
Star Contributor
Star Contributor
There's two parts to creating a share site.  The first is the repository configuration which is what you have done via the site service,  the second part is to configure share for the new site.   You will find other threads in this forum discussing this.

sans
Champ in-the-making
Champ in-the-making
I guess you are talking about calling the create-site.post.json.js.
How do I call create-site.post.json.js through my java code?

Thanks
Sans.

sans
Champ in-the-making
Champ in-the-making
Hi,
Now I have changed my code. I am using ScriptSiteService to create the site.
Here is the code snippet.
package org.alfresco.sample;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.ScriptService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.cmr.site.SiteInfo;
import org.alfresco.service.cmr.site.SiteService;
import org.alfresco.service.cmr.site.SiteVisibility;
import org.alfresco.service.cmr.tagging.TaggingService;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.GUID;
import org.alfresco.util.PropertyMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.extensions.webscripts.AbstractWebScript;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
import org.springframework.extensions.webscripts.WebScriptException;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.jscript.BaseScopableProcessorExtension;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.repo.site.script.ScriptSiteService;
import org.alfresco.sample.webservice.AlfrescoCreateUser;

public class AlfrescoCreateSite //extends ScriptSiteService//BaseWebScriptTest //AbstractWebScript//extends BaseAlfrescoSpringTest
{
    private static final String TEST_SITE_PRESET = "testSitePreset";
    private static final String TEST_TITLE = "This is my title";
    private static final String TEST_URL = "test_url";
    private static final String TEST_DESCRIPTION = "This is my description";
    private static final String USER_ONE = "admin";
    private SiteService siteService;   
    private ScriptService scriptService;
    private ScriptSiteService scriptSiteService;
    private SearchService searchService;
    private NodeService nodeService;
    private AuthenticationComponent authenticationComponent;
    private TaggingService taggingService;
    private PersonService personService;
    private AuthorityService authorityService;
    private ApplicationContext applicationContext;
    private AuthenticationService authenticationService;
    private char[] pass = {'a','d','m','i','n'};
    private static final String URL_SITES = "/api/sites";
    private static final String URL_SITES_QUERY = URL_SITES + "/query";
    private static final String URL_MEMBERSHIPS = "/memberships";
    private String shortName = null;
    private String groupOne;
   
    public static void main(String[] args) throws Exception {
        AlfrescoCreateSite obj = new AlfrescoCreateSite();
        obj.onSetUpInTransaction();
        //obj.setUp();
        obj.testCreateSite();
        System.out.print("Site Created in Repo but not in Share");
      }
   
    protected void onSetUpInTransaction() throws Exception
    {
        // Get the required services
        applicationContext = ApplicationContextHelper.getApplicationContext();
        siteService = (SiteService)this.applicationContext.getBean("SiteService");
        scriptService = (ScriptService)this.applicationContext.getBean("ScriptService");
        this.scriptSiteService = (ScriptSiteService)this.applicationContext.getBean("siteServiceScript");
        this.authenticationComponent = (AuthenticationComponent)this.applicationContext.getBean("authenticationComponent");
        authorityService = (AuthorityService)this.applicationContext.getBean("AuthorityService");
        this.authenticationComponent.authenticate(USER_ONE, pass);
       
        this.authenticationComponent.setCurrentUser(USER_ONE);
    }
   
    public void testCreateSite() throws Exception
    {
        shortName  = GUID.generate();
        this.scriptSiteService.createSite("site-dashboard", shortName, "myTitle", "myDescription", (SiteVisibility.PUBLIC).toString());
    }
   
     public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException
    {
        try
        {
            // build a json object
            JSONObject site = new JSONObject();
           
           
            // put some data on it
            site.put("sitePreset", "site-dashboard");
            site.put("shortName", shortName);
            site.put("title", "myTitle");
            site.put("description", "myDescription");
            site.put("visibility", (SiteVisibility.PUBLIC).toString());
           
            // build a JSON string and send it back
            String jsonString = site.toString();
            res.getWriter().write(jsonString);
        }
        catch(JSONException e)
        {
                throw new WebScriptException("Unable to serialize JSON");
        }
    } 
   private void checkSiteInfo(SiteInfo siteInfo,
            String expectedSitePreset,
            String expectedShortName,
            String expectedTitle,
            String expectedDescription,
            SiteVisibility expectedVisibility)
    {
        junit.framework.Assert.assertNotNull(siteInfo);
        junit.framework.Assert.assertEquals(expectedSitePreset, siteInfo.getSitePreset());
        junit.framework.Assert.assertEquals(expectedShortName, siteInfo.getShortName());
        junit.framework.Assert.assertEquals(expectedTitle, siteInfo.getTitle());
        junit.framework.Assert.assertEquals(expectedDescription, siteInfo.getDescription());
        junit.framework.Assert.assertEquals(expectedVisibility, siteInfo.getVisibility());
    }
}

But I am getting the exception. Here is the exception…

Exception in thread "main" org.alfresco.error.AlfrescoRuntimeException: 10300001 Transaction must be active and synchronization is required: Thread[main,5,main]
   at org.alfresco.repo.transaction.AlfrescoTransactionSupport.registerSynchronizations(AlfrescoTransactionSupport.java:452)
   at org.alfresco.repo.transaction.AlfrescoTransactionSupport.getSynchronization(AlfrescoTransactionSupport.java:436)
   at org.alfresco.repo.transaction.AlfrescoTransactionSupport.getResource(AlfrescoTransactionSupport.java:229)
   at org.alfresco.repo.transaction.TransactionalResourceHelper.getSet(TransactionalResourceHelper.java:66)
   at org.alfresco.repo.node.db.DbNodeServiceImpl.isDeletedNodeRef(DbNodeServiceImpl.java:393)
   at org.alfresco.repo.node.db.DbNodeServiceImpl.createNode(DbNodeServiceImpl.java:289)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
   at java.lang.reflect.Method.invoke(Unknown Source)
   at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
   at org.alfresco.repo.tenant.MultiTNodeServiceInterceptor.invoke(MultiTNodeServiceInterceptor.java:104)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
   at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
   at $Proxy7.createNode(Unknown Source)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
   at java.lang.reflect.Method.invoke(Unknown Source)
   at org.alfresco.repo.service.StoreRedirectorProxyFactory$RedirectorInvocationHandler.invoke(StoreRedirectorProxyFactory.java:215)
   at $Proxy8.createNode(Unknown Source)
   at org.alfresco.repo.security.authority.AuthorityDAOImpl.createAuthority(AuthorityDAOImpl.java:221)
   at org.alfresco.repo.security.authority.AuthorityServiceImpl.createAuthority(AuthorityServiceImpl.java:408)
   at org.alfresco.repo.site.SiteServiceImpl$1.doWork(SiteServiceImpl.java:402)
   at org.alfresco.repo.site.SiteServiceImpl$1.doWork(SiteServiceImpl.java:394)
   at org.alfresco.repo.security.authentication.AuthenticationUtil.runAs(AuthenticationUtil.java:508)
   at org.alfresco.repo.site.SiteServiceImpl.createSite(SiteServiceImpl.java:393)
   at org.alfresco.repo.site.script.ScriptSiteService.createSite(ScriptSiteService.java:103)
   at org.alfresco.sample.AlfrescoCreateSite.testCreateSite(AlfrescoCreateSite.java:167)
   at org.alfresco.sample.AlfrescoCreateSite.main(AlfrescoCreateSite.java:99)
Any thoughts on this?

Thanks
sans!!!

sans
Champ in-the-making
Champ in-the-making
Here is the code:
String alf_ticket = getAlfTicket("admin", "admin");
            JSONObject site = new JSONObject();
            site.put("sitePreset", "site-dashboard");
            site.put("shortName", shortName);
            site.put("title", "myTitle"+shortName.substring(0,4));
            site.put("description", "myDescription");
            site.put("visibility", ScriptSiteService.PUBLIC_SITE);               
            site.put("ticket", alf_ticket);
            //client.getParams().setAuthenticationPreemptive(true);
            client.getState().setCredentials(new AuthScope("localhost", 8080), new UsernamePasswordCredentials("admin", "admin"));
           
            //post = new PostMethod("http://localhost:8080/share/service/modules/create-site?alf_ticket='+alf_ticket);
            //post = new PostMethod("http://localhost:8080/alfresco/s/api/sites?alf_ticket='+alf_ticket);
           
            post = new PostMethod("http://localhost:8080/share/service/modules/create-site?ticket='+alf_ticket);//Working one
            //post = new PostMethod("http://localhost:8080/share/service/modules/create-site?alf_ticket='+alf_ticket);
            //post = new GetMethod("http://localhost:8080/share/page/modules/create-site");
            post.setDoAuthentication(true);
            post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
            post.setRequestHeader("Accept-Charset", "ISO-8859-1,UTF-8");
            post.setRequestHeader("Accept-Language", "en");
            post.setRequestHeader("Content_Type", "application/json");
            //post.addParameter("alf_ticket", alf_ticket);
            System.out.println("Authorization Header Before >>>"+post.getRequestHeader("Authorization"));
            String userid = "admin";
            String password = "admin";
            String stringUserIdPassword = userid + ":" + password;

            byte[] byteUserIdPassword = stringUserIdPassword.getBytes( "ASCII" );

            byte[] base64UserIdPassword = new Base64().encode( byteUserIdPassword );
            post.setRequestHeader("Authorization", "BASIC "+base64UserIdPassword.toString());
            System.out.println("Authorization Header After >>>"+post.getRequestHeader("Authorization"));           
           
            post.setRequestEntity(new StringRequestEntity(site.toString(),"application/json", "UTF-8"));
            RequestEntity reqEnt = post.getRequestEntity();
            reqEnt.writeRequest(System.out);
            System.out.println();
            System.out.println("Request Entity>>> "+reqEnt.getContentType());
           
            Header[] head = post.getRequestHeaders();
            for(Header hea : head)
            {
                System.out.println("Headers >>>"+hea.toString());
            }
            statusCode = client.executeMethod(post);
           
            System.out.println("Status Text>>>"+HttpStatus.getStatusText(statusCode));
            System.out.println("ResponseBody json"+post.getResponseBodyAsString());
            post.releaseConnection();
public String getAlfTicket(String _userName, String _password)
    {
       String _ticket = "";

       URL url;
       HttpURLConnection connection = null;
       try
       {
          String urlParameters = "{ \"username\" : \"" + _userName +"\", \"password\" : \"" + _password +"\" }";
         
          // Create connection
          url = new URL("http://localhost:8080/alfresco/service/api/login");
          connection = (HttpURLConnection) url.openConnection();

          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type", "application/json");
          connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
          connection.setRequestProperty("Content-Language", "en-US");
          connection.setUseCaches(false);
          connection.setDoInput(true);
          connection.setDoOutput(true);

          // Send request
          DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
          wr.writeBytes(urlParameters);
          wr.flush();
          wr.close();

          // Get Response
          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer();
          while ((line = rd.readLine()) != null)
          {
             response.append(line);
             response.append('\r');
          }
          rd.close();
          String _jsonResponse = response.toString();
         
          org.json.simple.JSONObject _jsonResponseObject = (org.json.simple.JSONObject) new JSONParser().parse(_jsonResponse);
          org.json.simple.JSONObject jsonDataObject = (org.json.simple.JSONObject)new JSONParser().parse(_jsonResponseObject.get("data").toString());
           _ticket = jsonDataObject.get("ticket").toString();

       }
       catch (Exception e)
       {

          e.printStackTrace();
          return null;

       }
       finally
       {

          if (connection != null)
          {
             connection.disconnect();
          }
       }
       return _ticket;
    }

carolanna
Champ in-the-making
Champ in-the-making
hi sans,
     i just want to know the code above is it a simple java or a servlet class.And how can use various org.alfresco packages into my program.

sans
Champ in-the-making
Champ in-the-making
Hi Carol,
This can be written as a plain java code or as a servlet class.
To use all alfresco related packages you will have to set your classpath to point to SDK AlfrescoEmbedded and SDK AlfrescoRemote projects.
These projects will be available when you download the SDK for alfresco.

Thanks
Sanjay

patil
Champ on-the-rise
Champ on-the-rise
Hi Sanjay,
I tried the code with no success. Am I missing anything in the file?

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.alfresco.repo.site.script.ScriptSiteService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;

/**
*
*/

/**
* @author basanagowda.patil
*
*/
public class SiteCreation {

   /**
    * @param args
    * @throws JSONException
    * @throws IOException
    */
   public static void main(String[] args) throws JSONException, IOException {
      String shortName = "basanagowda";
       String alf_ticket = getAlfTicket("admin", "admin");
        JSONObject site = new JSONObject();
        site.put("sitePreset", "site-dashboard");
        site.put("shortName", shortName);
        site.put("title", "myTitle"+shortName.substring(0,4));
        site.put("description", "myDescription");
        site.put("visibility", ScriptSiteService.PUBLIC_SITE);              
        site.put("ticket", alf_ticket);
        //client.getParams().setAuthenticationPreemptive(true);
        HttpClient client = new HttpClient();
        client.getState().setCredentials(new AuthScope("localhost", 8080), new UsernamePasswordCredentials("admin", "admin"));
      
        //post = new PostMethod("http://localhost:8080/share/service/modules/create-site?alf_ticket='+alf_ticket);
        //post = new PostMethod("http://localhost:8080/alfresco/s/api/sites?alf_ticket='+alf_ticket);
      
        PostMethod post = new PostMethod("http://localhost:8080/share/service/modules/create-site?ticket='+alf_ticket);//Working one
        //post = new PostMethod("http://localhost:8080/share/service/modules/create-site?alf_ticket='+alf_ticket);
        //post = new GetMethod("http://localhost:8080/share/page/modules/create-site");
        post.setDoAuthentication(true);
        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        post.setRequestHeader("Accept-Charset", "ISO-8859-1,UTF-8");
        post.setRequestHeader("Accept-Language", "en");
        post.setRequestHeader("Content_Type", "application/json");
        //post.addParameter("alf_ticket", alf_ticket);
        System.out.println("Authorization Header Before >>>"+post.getRequestHeader("Authorization"));
        String userid = "admin";
        String password = "admin";
        String stringUserIdPassword = userid + ":" + password;

        byte[] byteUserIdPassword = stringUserIdPassword.getBytes( "ASCII" );

        byte[] base64UserIdPassword = new Base64().encode( byteUserIdPassword );
        post.setRequestHeader("Authorization", "BASIC "+base64UserIdPassword.toString());
        System.out.println("Authorization Header After >>>"+post.getRequestHeader("Authorization"));          
      
        post.setRequestEntity(new StringRequestEntity(site.toString(),"application/json", "UTF-8"));
        RequestEntity reqEnt = post.getRequestEntity();
        reqEnt.writeRequest(System.out);
        System.out.println();
        System.out.println("Request Entity>>> "+reqEnt.getContentType());
      
        Header[] head = post.getRequestHeaders();
        for(Header hea : head)
        {
            System.out.println("Headers >>>"+hea.toString());
        }
       int statusCode = client.executeMethod(post);
      
        System.out.println("Status Text>>>"+HttpStatus.getStatusText(statusCode));
        System.out.println("ResponseBody json"+post.getResponseBodyAsString());
        post.releaseConnection();


      
      

   }
   
   
   public static String getAlfTicket(String _userName, String _password)
   {
      String _ticket = "";

      URL url;
      HttpURLConnection connection = null;
      try
      {
         String urlParameters = "{ \"username\" : \"" + _userName +"\", \"password\" : \"" + _password +"\" }";
       
         // Create connection
         url = new URL("http://localhost:8080/alfresco/service/api/login");
         connection = (HttpURLConnection) url.openConnection();

         connection.setRequestMethod("POST");
         connection.setRequestProperty("Content-Type", "application/json");
         connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
         connection.setRequestProperty("Content-Language", "en-US");
         connection.setUseCaches(false);
         connection.setDoInput(true);
         connection.setDoOutput(true);

         // Send request
         DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
         wr.writeBytes(urlParameters);
         wr.flush();
         wr.close();

         // Get Response
         InputStream is = connection.getInputStream();
         BufferedReader rd = new BufferedReader(new InputStreamReader(is));
         String line;
         StringBuffer response = new StringBuffer();
         while ((line = rd.readLine()) != null)
         {
            response.append(line);
            response.append('\r');
         }
         rd.close();
         String _jsonResponse = response.toString();
       
         org.json.simple.JSONObject _jsonResponseObject = (org.json.simple.JSONObject) new JSONParser().parse(_jsonResponse);
         org.json.simple.JSONObject jsonDataObject = (org.json.simple.JSONObject)new JSONParser().parse(_jsonResponseObject.get("data").toString());
          _ticket = jsonDataObject.get("ticket").toString();
System.out.println(_ticket);
      }
      catch (Exception e)
      {

         e.printStackTrace();
         return null;

      }
      finally
      {

         if (connection != null)
         {
            connection.disconnect();
         }
      }
      return _ticket;
   }

}


I am getting the below response

TICKET_e3feaae7c28bbd693fea4c79adc33fe8f61a84ef
Authorization Header Before >>>null
Authorization Header After >>>Authorization: BASIC [B@65a77f

{"title":"myTitlebasa","ticket":"TICKET_e3feaae7c28bbd693fea4c79adc33fe8f61a84ef","visibility":"PUBLIC","description":"myDescription","sitePreset":"site-dashboard","shortName":"basanagowda"}
Request Entity>>> application/json; charset=UTF-8
Headers >>>Accept-Charset: ISO-8859-1,UTF-8

Headers >>>Accept-Language: en

Headers >>>Content_Type: application/json

Headers >>>Authorization: BASIC [B@65a77f

Status Text>>>Unauthorized
ResponseBody json{
    "status" :
  {
    "code" : 401,
    "name" : "Unauthorized",
    "description" : "The request requires HTTP authentication."
  }, 
 
  "message" : "error.loggedOut", 
  "exception" : "",
 
  "callstack" :
  [
       
  ],
 
  "server" : "Spring WebScripts - v1.0.0 (Release Candidate 2 804) schema 1,000",
  "time" : "Sep 19, 2011 11:09:26 PM"
}





Thanks,
Patil

sans
Champ in-the-making
Champ in-the-making
Hi Patil,
Did you get this response in debug mode or run mode? My diagnose is your request is timing out in debug mode.