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

patil
Champ on-the-rise
Champ on-the-rise
In run mode.

Thanks,
Patil

sans
Champ in-the-making
Champ in-the-making
Try this new class
public class CrestSiteService
{
   //private String                   ticket       = null;
   //private final String             user       = "admin";
   //private final String             password    = "admin";
   //private String                  shortName   = null;
   private static final String          HEADER_CONTENT_TYPE = "Content-Type";
   private static final String          CONTENT_TYPE_JSON = "application/json";
   private static final String          UTF_8 = "UTF-8";
   private static final String          CONTENT_TYPE_TEXT_PLAIN = "text/plain";
   private static final Log logger = LogFactory.getLog(CrestSiteService.class);
   
    /*private String getUser()
    {
       return this.user;
    }
    private String getPassword()
    {
       return this.password;
    }
    private String getTicket()
    {
        return this.ticket;
    }
    private void setTicket(String ticket)
    {
       this.ticket = ticket;
    }
    private String getShortName()
    {
       return this.shortName;
    }
    private void setShortName()
    {
       this.shortName = GUID.generate().substring(0, 4);
    }*/
   
    private String getSiteBody(String shortName, String title, String description, boolean isPublic) throws JSONException
   {
      JSONObject site = new JSONObject();
        site.put("sitePreset", "site-dashboard");
        site.put("shortName", shortName);
        site.put("title", title);
        site.put("description", description);
        if(isPublic)
           site.put("visibility", ScriptSiteService.PUBLIC_SITE);
        else
           site.put("visibility", ScriptSiteService.PRIVATE_SITE);
        //site.put("alf_ticket", getTicket());
        return site.toString();
   }
   
   public boolean createSite(String url, String ticket, String shortName, String title, String description, boolean isPublic)
    {
        HttpClient httpClient = new HttpClient();
        boolean siteCreated = false;
        //String createSiteBody = "{\"isPublic\":\"" + isPublic + "\",\"title\":\"" + title + "\",\"shortName\":\"" + shortName + "\"," + "\"description\":\"" + description
        //        + "\",\"sitePreset\":\"" + sitePreset + "\"" + (isPublic ? ",\"alfresco-createSite-instance-isPublic-checkbox\":\"on\"}" : "}");
       PostMethod createSiteMethod = null;
        try
        {
           //AuthenticationUtils.startSession(userName, password);
           //String ticket = AuthenticationUtils.getTicket();
           
           //Get a JSON string with the site details.
           String createSiteBody = getSiteBody(shortName, title, description, isPublic);
           
           //Create post method
            createSiteMethod = createPostMethod(url+"/s/api/sites?alf_ticket=" + ticket, createSiteBody, CONTENT_TYPE_JSON);

           if (logger.isDebugEnabled()) logger.debug("Trying to create site with name: " + shortName + ". URL: " + createSiteMethod.getURI());
           
           //Execute the post method
            int createSiteStatus = httpClient.executeMethod(createSiteMethod);
           
            //createSiteMethod.getResponseBody();
            if (logger.isDebugEnabled()) logger.debug("Create site method returned status: " + createSiteStatus);
            if(createSiteStatus == 200)
            {
               // create title sites component
               siteCreated = createComponent(url, httpClient, shortName, ticket, "title", "title/collaboration-title");

                // create navigation sites component
               siteCreated = createComponent(url, httpClient, shortName, ticket, "navigation", "navigation/collaboration-navigation");

                // create component-1-1 sites component
               siteCreated = createComponent(url, httpClient, shortName, ticket, "component-1-1", "dashlets/site-welcome");

                // create component-2-1 sites component
               siteCreated = createComponent(url, httpClient, shortName, ticket, "component-2-1", "dashlets/docsummary");

                // create component-2-2 sites component       
               siteCreated = createComponent(url, httpClient, shortName, ticket, "component-2-2", "dashlets/activityfeed");
               
                // create component-3-1 sites component       
               siteCreated = createComponent(url, httpClient, shortName, ticket, "component-3-1", "dashlets/site-profile");
               
                // create component-3-2 sites component       
               siteCreated = createComponent(url, httpClient, shortName, ticket, "component-3-2", "dashlets/colleagues");
               
                // create component-3-3 sites component       
               siteCreated = createComponent(url, httpClient, shortName, ticket, "component-3-3", "dashlets/site-links");
               
                // create documetnLibrary folder
               siteCreated = createDocumentLibrary(url, httpClient, shortName, ticket);

                // create sites dashboard
               siteCreated = createSiteDashboard(url, httpClient, shortName, ticket);
               
                // create links folder
               siteCreated = createLinks(url, httpClient, shortName, ticket);
            }
        }
        catch (HttpException he)
        {
           if (logger.isDebugEnabled()) logger.debug("Fail to create site with name: " + shortName + ". Message: " + he.getMessage());
           //throw new RuntimeException(he);
        }
        catch (AuthenticationFault ae)
        {
           if (logger.isDebugEnabled()) logger.debug("Fail to create site with name: " + shortName + ". Message: " + ae.getMessage());
           //throw new RuntimeException(ae);
        }
        catch (IOException ioe)
        {
           if (logger.isDebugEnabled()) logger.debug("Fail to create site with name: " + shortName + ". Message: " + ioe.getMessage());
           //throw new RuntimeException(ioe);
        }
        catch (JSONException je)
        {
           if (logger.isDebugEnabled()) logger.debug("Fail to create site with name: " + shortName + ". Message: " + je.getMessage());
           //throw new RuntimeException(je);
        }
        finally
        {
            createSiteMethod.releaseConnection();
        }
        return siteCreated;
    }

   private boolean createComponent(String url, HttpClient httpClient, String siteName, String ticket, String componentName, String componentURL)
    {
      boolean componentCreated = false;
        String compUrl = url+"/s/remotestore/create/alfresco/site-data/components/page." + componentName + ".site~" + siteName
                + "~dashboard.xml?s=sitestore&alf_ticket=" + ticket;
       
        String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "<component>\n" +
                            "<guid>page." + componentName + ".site~" + siteName + "~dashboard</guid>\n" +
                            "<scope>page</scope>\n" +
                            "<region-id>" + componentName + "</region-id>\n" +
                            "<source-id>site/" + siteName + "/dashboard</source-id>\n" +
                            "<url>/components/" + componentURL + "</url>\n" +
                        "</component>";
       
        PostMethod postMethod = null;
        try
        {
           postMethod = createPostMethod(compUrl, body, "application/octet-stream");
           if (logger.isDebugEnabled()) logger.debug("Trying to create site component with name: " + componentName + ". URL: " + postMethod.getURI());

            int status = httpClient.executeMethod(postMethod);
            //postMethod.getResponseBody();
            if(status == 200)
               componentCreated = true;
            if (logger.isDebugEnabled()) logger.debug("Create component with name: " + componentName + ". Method returned status: " + status);
        }
        catch (Exception e)
        {
           if (logger.isDebugEnabled()) logger.debug("Fail to create site component with name: " + componentName + ". Message: " + e.getMessage());
           //throw new RuntimeException(e);
        }
        finally
        {
            postMethod.releaseConnection();
        }
        return componentCreated;
    }
   
    /**
     * Creates site dashboard
     *
     * @param httpClient HTTP client
     * @param siteName name of the site
     * @param user current user
     * @throws UnsupportedEncodingException
     */
    private boolean createSiteDashboard(String url, HttpClient httpClient, String siteName, String ticket) throws UnsupportedEncodingException
    {
       boolean dashboardCreated = false;
        String createSiteDashboardBody = "";
        createSiteDashboardBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<page>\n" +
            "<title>Collaboration Site Dashboard</title>\n" +
            "<title-id>page.collaboration_site.title</title-id>\n" +
            "<description>Collaboration Site dashboard page</description>\n" +
            "<description-id>page.collaboration_site.description</description-id>\n" +
            "<template-instance>dashboard-3-columns</template-instance>\n" +
            "<authentication>user</authentication>\n" +
            "<properties>\n" +
                "<sitePages>" +
                "["+
                "{\"pageId\":\"wiki-page\"}," +
                "{\"pageId\":\"blog-postlist\"}," +
                "{\"pageId\":\"documentlibrary\"}," +
                "{\"pageId\":\"calendar\"}," +
                "{\"pageId\":\"links\"}," +
                "{\"pageId\":\"discussions-topiclist\"}," +
                "{\"pageId\":\"data-lists\"}," +
                "]" +
                "</sitePages>\n" +
            "</properties>\n" +
        "</page>";

        PostMethod createSiteDashboardMethod = createPostMethod(url+"/s/remotestore/create/alfresco/site-data/pages/site/" + siteName
                + "/dashboard.xml?s=sitestore&alf_ticket=" + ticket, createSiteDashboardBody, "application/octet-stream");
        try
        {
           if (logger.isDebugEnabled()) logger.debug("Trying to create site dashboard. URL: " + createSiteDashboardMethod.getURI());

            int status = httpClient.executeMethod(createSiteDashboardMethod);
            createSiteDashboardMethod.getResponseBody();
            if(status == 200)
               dashboardCreated = true;
            if (logger.isDebugEnabled()) logger.debug("Create site dashboard method returned status: " + status);
        }
        catch (Exception e)
        {
           if (logger.isDebugEnabled()) logger.debug("Fail to create site dashboard. Message: " + e.getMessage());
           //throw new RuntimeException(e);
        }
        finally
        {
            createSiteDashboardMethod.releaseConnection();
        }
        return dashboardCreated;
    }
   
    /**
     * Creates documentLibrary folder in site
     *
     * @param httpClient HTTP client
     * @param siteName short name of site
     * @param user current user
     */
    private boolean createDocumentLibrary(String url, HttpClient httpClient, String siteName, String ticket)
    {
       boolean docLibCreated = false;
        GetMethod createDocumentLibraryFolderMethod = createGetMethod(url+"/s/slingshot/doclib/doclist/documents/site/" + siteName
                + "/documentLibrary?filter=recentlyModified&max=10&alf_ticket=" + ticket);
        try
        {
           if (logger.isDebugEnabled()) logger.debug("Trying to create sites documentLibrary folder. URL: " + createDocumentLibraryFolderMethod.getURI());
           
            int status = httpClient.executeMethod(createDocumentLibraryFolderMethod);
            createDocumentLibraryFolderMethod.getResponseBody();
            if(status == 200)
               docLibCreated = true;
            if (logger.isDebugEnabled()) logger.debug("Create sites documentLibrary folder method returned status: " + status);
        }
        catch (Exception e)
        {
           if (logger.isDebugEnabled()) logger.debug("Fail to create sites documentLibrary folder. Message: " + e.getMessage());
           //throw new RuntimeException(e);
        }
        finally
        {
            createDocumentLibraryFolderMethod.releaseConnection();
        }
        return docLibCreated;
    }
   
    /**
     * Creates links folder in site
     *
     * @param httpClient HTTP client
     * @param siteName short name of site
     * @param user current user
     */
    private boolean createLinks(String url, HttpClient httpClient, String siteName, String ticket)
    {
       boolean linksCreated = false;
        GetMethod createLinksFolderMethod = createGetMethod(url+"/s/api/links/site/" + siteName + "/links?page=1&pageSize=512&alf_ticket="
                + ticket);
        try
        {
           if (logger.isDebugEnabled()) logger.debug("Trying to create site links folder. URL: " + createLinksFolderMethod.getURI());
           
            int status = httpClient.executeMethod(createLinksFolderMethod);
            createLinksFolderMethod.getResponseBody();
            if(status == 200)
               linksCreated = true;
            if (logger.isDebugEnabled()) logger.debug("Create site links folder method returned status: " + status);
        }
        catch (Exception e)
        {
            if (logger.isDebugEnabled()) logger.debug("Fail to create site links folder. Message: " + e.getMessage());
            //throw new RuntimeException(e);
        }
        finally
        {
            createLinksFolderMethod.releaseConnection();
        }
        return linksCreated;
    }
    /**
     * Creates POST method
     *
     * @param url URL for request
     * @param body body of request
     * @param contentType content type of request
     * @return POST method
     * @throws UnsupportedEncodingException
     */
    private PostMethod createPostMethod(String url, String body, String contentType) throws UnsupportedEncodingException
    {
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader(HEADER_CONTENT_TYPE, contentType);
        postMethod.setRequestEntity(new StringRequestEntity(body, CONTENT_TYPE_TEXT_PLAIN, UTF_8));

        return postMethod;
    }
   
    /**
     * Creates GET method
     *
     * @param url URL for request
     * @return GET method
     */
    private GetMethod createGetMethod(String url)
    {
        GetMethod getMethod = new GetMethod(url);
        return getMethod;
    }
   
    /*public static void main(String args[]) throws HttpException, IOException, JSONException
    {
       CrestSite site = new CrestSite();
       AuthenticationUtils.startSession(site.getUser(), site.getPassword());
       site.setTicket(AuthenticationUtils.getTicket());
       String ticket = AuthenticationUtils.getTicket();
       site.setShortName();
       //SessionUser user = new User(site.getUser(), site.getTicket());
       site.createSite(ticket, "shortName"+site.getShortName(), "title"+site.getShortName(), "desc"+site.getShortName(), true );
    }*/
}

mrinal3199
Champ in-the-making
Champ in-the-making
I am developing a custom search utility which will return the results of contents from that site only from which it has been triggered. So, i need to get this site name autmatically so that i can use that in my lucene query. I have gone through site service functions. They all are expecting an input either site name or their noderef which i don't want to pass as a parameter. Do you have any solution for that. I am able to get the current site name in javascript. So, there must be some solution to get the same from java also.

Thanks,
Mrinal  

thirumal
Champ on-the-rise
Champ on-the-rise
I have used the above code to create share site it's creating the st:site node but it does not create the dashboard page. I am getting the following error while redirecting to the created page.

2015-02-06 14:28:35,541  DEBUG [] [http-bio-8080-exec-1] Response: TICKET_e2f8b5953fd182dd28982f130598f08bad46bc71
2015-02-06 14:28:35,541  DEBUG [] [http-bio-8080-exec-1] Inside createSite
2015-02-06 14:28:35,541  DEBUG [] [http-bio-8080-exec-1] Inside getSiteBody
2015-02-06 14:28:35,541  DEBUG [] [http-bio-8080-exec-1] Trying to create site with name: shortName85de. URL: http://localhost:8080/alfresco/s/api/sites?alf_ticket=TICKET_e2f8b5953fd182dd28982f130598f08bad46bc7...
2015-02-06 14:28:35,683  DEBUG [] [http-bio-8080-exec-1] Create site method returned status: 200
2015-02-06 14:28:35,684  DEBUG [] [http-bio-8080-exec-1] Trying to create site component with name: title. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/components/page.title.site~short...
2015-02-06 14:28:35,715  DEBUG [] [http-bio-8080-exec-1] Create component with name: title. Method returned status: 200
2015-02-06 14:28:35,716  DEBUG [] [http-bio-8080-exec-1] Trying to create site component with name: navigation. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/components/page.navigation.site~...
2015-02-06 14:28:35,739  DEBUG [] [http-bio-8080-exec-1] Create component with name: navigation. Method returned status: 200
2015-02-06 14:28:35,739  DEBUG [] [http-bio-8080-exec-1] Trying to create site component with name: component-1-1. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/components/page.component-1-1.si...
2015-02-06 14:28:35,767  DEBUG [] [http-bio-8080-exec-1] Create component with name: component-1-1. Method returned status: 200
2015-02-06 14:28:35,780  DEBUG [] [http-bio-8080-exec-1] Trying to create site component with name: component-2-1. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/components/page.component-2-1.si...
2015-02-06 14:28:35,805  DEBUG [] [http-bio-8080-exec-1] Create component with name: component-2-1. Method returned status: 200
2015-02-06 14:28:35,805  DEBUG [] [http-bio-8080-exec-1] Trying to create site component with name: component-2-2. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/components/page.component-2-2.si...
2015-02-06 14:28:35,836  DEBUG [] [http-bio-8080-exec-1] Create component with name: component-2-2. Method returned status: 200
2015-02-06 14:28:35,836  DEBUG [] [http-bio-8080-exec-1] Trying to create site component with name: component-3-1. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/components/page.component-3-1.si...
2015-02-06 14:28:35,905  DEBUG [] [http-bio-8080-exec-1] Create component with name: component-3-1. Method returned status: 200
2015-02-06 14:28:35,905  DEBUG [] [http-bio-8080-exec-1] Trying to create site component with name: component-3-2. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/components/page.component-3-2.si...
2015-02-06 14:28:35,925  DEBUG [] [http-bio-8080-exec-1] Create component with name: component-3-2. Method returned status: 200
2015-02-06 14:28:35,926  DEBUG [] [http-bio-8080-exec-1] Trying to create site component with name: component-3-3. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/components/page.component-3-3.si...
2015-02-06 14:28:35,951  DEBUG [] [http-bio-8080-exec-1] Create component with name: component-3-3. Method returned status: 200
2015-02-06 14:28:35,951  DEBUG [] [http-bio-8080-exec-1] Trying to create sites documentLibrary folder. URL: http://localhost:8080/share/s/slingshot/doclib/doclist/documents/site/shortName85de/documentLibrary?...
2015-02-06 14:28:35,979  DEBUG [] [http-bio-8080-exec-1] Create sites documentLibrary folder method returned status: 200
2015-02-06 14:28:35,980  DEBUG [] [http-bio-8080-exec-1] Trying to create site dashboard. URL: http://localhost:8080/share/s/remotestore/create/alfresco/site-data/pages/site/shortName85de/dashboa...
2015-02-06 14:28:36,007  DEBUG [] [http-bio-8080-exec-1] Create site dashboard method returned status: 200
2015-02-06 14:28:36,007  DEBUG [] [http-bio-8080-exec-1] Trying to create site links folder. URL: http://localhost:8080/share/s/api/links/site/shortName85de/links?page=1&pageSize=512&alf_ticket=TICK...
2015-02-06 14:28:36,034  DEBUG [] [http-bio-8080-exec-1] Create site links folder method returned status: 200

Feb 06, 2015 2:33:39 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Spring Surf Dispatcher Servlet] in context with path [/share] threw exception [Could not resolve view with name 'site/shortNamee4ef/dashboard' in servlet with name 'Spring Surf Dispatcher Servlet'] with root cause
javax.servlet.ServletException: Could not resolve view with name 'site/shortNamee4ef/dashboard' in servlet with name 'Spring Surf Dispatcher Servlet'
   at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1183)
   at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:986)
   at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:933)
   at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
   at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
   at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
   at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
   at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
   at org.alfresco.web.site.servlet.MTAuthenticationFilter.doFilter(MTAuthenticationFilter.java:74)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
   at org.alfresco.web.site.servlet.SecurityHeadersFilter.doFilter(SecurityHeadersFilter.java:168)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
   at org.alfresco.web.site.servlet.CSRFFilter.doFilter(CSRFFilter.java:322)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
   at org.alfresco.web.site.servlet.SSOAuthenticationFilter.doFilter(SSOAuthenticationFilter.java:394)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
   at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
   at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
   at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
   at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
   at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
   at java.lang.Thread.run(Thread.java:724)

2015-02-06 14:33:39,083  ERROR [alfresco.web.site] [http-bio-8080-exec-1] javax.servlet.ServletException: Could not resolve view with name 'site/shortNamee4ef/dashboard' in servlet with name 'Spring Surf Dispatcher Servlet'

azivotic
Champ in-the-making
Champ in-the-making
Any progress on this? A got the same error as you Patil?! Any solution?

Regards,
Aleksandar