Powered By Blogger

Monday, February 6, 2012

Calling the WebScript from command line and Java class

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

/**
*
*/

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

/**
* Main class of entry point
*
* @param args
*/
public static void main(final String[] args) {
System.out.println("Lucene Backup is been triggered");
final String url = "http://ecmdev.patil.com/alfresco/wcservice/patils/tags/all";
final HttpClient client = new HttpClient();
final GetMethod httpGet = new GetMethod(url);

try {

httpGet.addRequestHeader("CTUSER", "HFPBB101");
client.executeMethod(httpGet);
final String response = (httpGet.getResponseBodyAsString());
System.out.println(response);


System.out.println("StatusText:::"+ httpGet.getStatusText());
httpGet.releaseConnection();

} catch (final Exception e) {
e.printStackTrace();
}

}
}




You can call the webscripts from the CURL .

1. By passing the header

curl --header "CTUSER:HFPBB01" http://ecmdev.patil.com/alfresco/wcservice/patil/tags/all

2. By passing username and password

curl -uhfpbb101:8999 http://ecmdev.patil.com/alfresco/s/cmis

The first one is the preferred approach. Now we can write the webscript which triggers lucene backup and call that webscript as mentioned above.


There are other ways of backing the lucene indexes trigger

1. JMX

2.Command line

Refer to the link http://wiki.alfresco.com/wiki/Backup_and_Restore#

3. To get the http code

curl -sL -w "%{http_code} %{url_effective}\\n" --header "CTUSER:55551" "http://halfd01.patil.com:8080/alfresco/wcservice/patils/tags/all" -o /dev/null

Control-M Tool to Schedule backups - command execution tool

This tool can be used with commands written in bash shell script, perl, python or java.
http://www.scheduler-usage.com/document/Documentation/CTMS/V6.3.01/57941.pdf

http://www.scribd.com/aneezanis/d/22694387-ControlM-Concepts-Guide

Thursday, February 2, 2012

Maven important tutorial

http://blog.3kbo.com/2009/02/20/maven-commands/

Creating Maven Projects

  • mvn archetype:create -DgroupId=com._3kbo -DartifactId=application (create a project for building a jar file )
  • mvn archetype:create -DgroupId=com._3kbo -DartifactId=webapplication -DarchetypeArtifactId=maven-archetype-webapp (create a web app project for building a war file)
  • mvn archetype:generate (Select the number of the desired archetype.)

Building, Testing, Packaging and Installing to the Repository

  • mvn clean (cleans the project, i.e. delete the target directory)
  • mvn compile (compiles the source code)
  • mvn test (if required compiles the source code, then runs the unit tests)
  • mvn package (compiles, tests then packages the jar or war file)
  • mvn clean install (cleans the project, compiles, tests, packages and installs the jar or war file)
  • mvn install (compiles, tests, packages and installs the jar or war file)
  • mvn -o install (compiles, tests, packages and installs the jar or war file in offline mode)
  • mvn -Dmaven.test.skip package (package without running the tests)
  • mvn -Dmaven.test.skip clean install (clean and install without running tests)
  • mvn -o test (test offline)

Unit Tests

  • mvn test –Dtest=AspectTest (run a specific test)
  • mvn test -Dtest=*ModelTest (run a subset of tests using regular expression. E.g. test all ModelTest classes)

Excluding log4j.properties from jar file

Move log4j.properties from src/main/resources to src/test/resources.
That way it gets picked up by the testResources for testing but excluded from the jar file.

Manually Install a file to the Repository

mvn install:install-file -DgroupId=com._3kbo -DartifactId=model -Dversion=1.0.0 -Dpackaging=jar -Dfile=new_file.jar

Set Java Build Version




org.apache.maven.plugins
maven-compiler-plugin

1.5
1.5



Documentation

The mvn site command builds a useful dependency tree at target/site/dependencies.html.

  • mvn site (generate documentation in the target/site directory)
  • mvn javadoc:javadoc (generate javadoc in target/site/apidocs directory )
  • mvn help:active-profiles (lists the profiles currently active)
  • mvn help:effective-pom (displays the effective POM for the current build)
  • mvn help:effective-settings (displays the calculated settings for the project, given any profile enhancement and the inheritance of the global settings into the user-level settings.)
  • mvn help:describe (describes the attributes of a plugin)

For large projects mvn site can run out of memory. Use MAVEN_OPTS in the mvn or mvn.bat script to allocate additional memory, e.g:

MAVEN_OPTS=”-Xmx512m -Xms256m -XX:MaxPermSize=128m”

Repositories

Jena http://jena.hpl.hp.com/repo
Jersey http://download.java.net/maven/2/
Maven Central http://www.ibiblio.org/maven2


Wednesday, February 1, 2012

Sharepoint flow in Alfresco 3.4.5


${vti.share.siteInBrowser}

${vti.share.siteSettings}

${vti.share.siteGroupMembership}

${vti.share.userInformation}

${vti.share.documentLibrary}

${vti.share.documentDetails}

${vti.share.calendar}



The above bean declaration is using properties defined in the vti.properties which are speciic to site.


vti.share.siteSettings=/page/site/.../customise-site

vti.share.siteGroupMembership=/page/site/.../site-members

vti.share.userInformation=/page/user/.../profile

vti.share.documentLibrary=/page/site/.../documentlibrary

vti.share.documentDetails=/page/site/.../document-details

vti.share.calendar=/page/site/.../calendar



In the run time these values will be used by MS office.


  • alfresco-vti-3.4.5.jar is using the code required for the sharepoint communication.


AlfrescoDwsServiceHandler has the implementation to replace the node id urls



String uuid = req.getParameter("nodeId");


String uri = req.getRequestURI();

String redirectTo;


if (uuid != null)

{

// open site in browser

final NodeRef siteNodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, uuid.toLowerCase());

redirectTo = pagesMap.get("siteInBrowser");

redirectTo = redirectTo.replace("...", siteNodeRef.getId());

}





  • Communication happens with MS office docs using WebService response.




here it is pointing to sites.








It talks about what info is required for integration in the class DwsServiceHandler


/**

* Returns information about a document workspace site and the lists it contains

*

* @param document the site-based URL of a document in a document library in the document workspace site

* @param id an optional document globally unique identifier (GUID)

* @param minimal determines whether the output includes information about the schemas, lists, documents, links, and tasks lists of a document workspace site

* @return DwsMetadata information about a document workspace site and the lists it contains ({@link DwsMetadata})

*/

public DwsMetadata getDWSMetaData(String documentURL, String id, boolean minimal) throws Exception;



If we have to support sharepoint protocol then we should have details about tasks,links and document list but in the normal doc we will not have this information.




The server will be done using the bean







The logs are as below


05:50:18,573 DEBUG [vti.web.VtiFilter] Checking request for VTI

05:50:18,573 DEBUG [vti.web.VtiFilter] Check authentication

05:50:18,591 DEBUG [module.vti.handler] Resolved file info for 'templatechange/_vti_bin/_vti_aut/author.dll' is null

05:50:18,596 DEBUG [module.vti.handler] Resolved file info for 'templatechange/_vti_bin/_vti_aut' is null

05:50:18,600 DEBUG [module.vti.handler] Resolved file info for 'templatechange/_vti_bin' is null

05:50:18,607 DEBUG [module.vti.handler] Resolved file info for 'templatechange' is FileInfo[name=templatechange, isFolder=true, nodeRef=workspace://SpacesStore/cb5eb9d0-81ad-43d3-8ef7-c059b1b88704]

05:50:18,617 DEBUG [alfresco.v3.AlfrescoMethodHandler] WebUrl: /alfresco/templatechange, fileUrl: '_vti_bin/_vti_aut/author.dll'

05:50:18,634 DEBUG [vti.web.VtiFilter] User was authenticated successfully

05:50:18,635 DEBUG [vti.web.VtiRequestDispatcher] Process request

05:50:18,635 DEBUG [vti.web.VtiRequestDispatcher] Find appropriate action by specific rules

05:50:18,635 DEBUG [vti.web.VtiRequestDispatcher] Specific rule not found

05:50:18,635 DEBUG [vti.web.VtiRequestDispatcher] Find appropriate action by pattern for uri='/templatechange/_vti_bin/_vti_aut/author.dll'

05:50:18,635 DEBUG [vti.web.VtiRequestDispatcher] Action found for request

05:50:18,635 DEBUG [vti.web.VtiRequestDispatcher] Execute target action

05:50:18,636 DEBUG [web.actions.VtiBinAction] Executing vtiMethod: org.alfresco.module.vti.web.fp.CheckoutDocumentMethod@3941f799

05:50:18,636 DEBUG [web.fp.CheckoutDocumentMethod] Start method execution. Method name: checkout document

05:50:18,636 DEBUG [handler.alfresco.AbstractAlfrescoMethodHandler] Checkout document: documentLibrary/test.doc. Site name: templatechange

05:50:18,647 DEBUG [module.vti.handler] Resolved file info for 'templatechange/documentLibrary/test.doc' is FileInfo[name=test.doc, isFolder=false, nodeRef=workspace://SpacesStore/ee54a9a8-837a-43f1-b02e-276d2603861a]

05:50:18,704 DEBUG [handler.alfresco.AbstractAlfrescoMethodHandler] Short-term checkout.

05:50:18,870 DEBUG [module.vti.handler] Convert FileInfo[name=test.doc, isFolder=false, nodeRef=workspace://SpacesStore/ee54a9a8-837a-43f1-b02e-276d2603861a] to url path 'templatechange/documentLibrary/test.doc'

05:50:18,871 DEBUG [web.fp.CheckoutDocumentMethod] End of method execution. Method name: checkout document




The flow will be



Filter → Handler →Request Dispatcher → Action(VtiBinAction) → Method




Authentication itself is been checked using the siteservice in the Group AlfrescoUserGroupServiceHandler.


/**

* @see org.alfresco.module.vti.handler.UserGroupServiceHandler#isUserMember(java.lang.String, java.lang.String)

*/

public boolean isUserMember(String dwsUrl, String username)

{

// Normalize the user ID taking into account case sensitivity settings

String normalized = personService.getUserIdentifier(username);

if (normalized == null)

{

return false;

}

boolean isMember = siteService.isMember(dwsUrl, normalized);

if (!isMember && authorityService.isAdminAuthority(username))

{

// Admin is allowed to do things even on sites they're not

// a member of. So, pretend they are a member so they're allowed

isMember = true;

}

return isMember;

}




In the DefaultAuthenticationHandler class it checks whether user belongs to site or not


authenticateRequest() → which inturn checks for whether user belongs to site or not. All the requests will be going through the filter and filter calls authentication code. There it fails since the user is not belonging to any of the site.



Conclusion :

All the requests will be passing through the filter which checks whether user belongs to any of the site or not. If the user is not member of the site then user will be stopped from accssing the document.


VtiFilter checks with authenticationhandler.


user = authenticationHandler.authenticateRequest(this.context, httpRequest, httpResponse, getAlfrescoContext());




public SessionUser authenticateRequest(ServletContext context, HttpServletRequest request, HttpServletResponse response,

String alfrescoContext) throws IOException, ServletException

{

if (delegate.authenticateRequest(context, request, response))

{

HttpSession session = request.getSession(false);

if (session == null)

{

return null;

}

SessionUser user = (SessionUser) session.getAttribute(USER_SESSION_ATTRIBUTE);

if (user == null)

{

return null;

}

if(isSiteMember(request, alfrescoContext, user.getUserName()))

{

return user;

}

delegate.restartLoginChallenge(context, request, response);

}

return null;

}


It checks of the user belongs to site. If not it gives back null.





Next topic



/**

* @see org.alfresco.module.vti.handler.MeetingServiceHandler#createWorkspace(String, String, int, TimeZoneInformation, SessionUser)

*/

public String createWorkspace(String title, String templateName, int lcid, TimeZoneInformation timeZoneInformation, SessionUser user) throws Exception

{

title = removeIllegalCharacters(title);


if (title.equals("_"))

{

throw new RuntimeException(getMessage("vti.meeting.error.workspace_name"));

}


SiteInfo siteInfo = null;

String newTitle = null;

int i = 0;

do

{

newTitle = title + (i == 0 ? "" : "_" + i);

siteInfo = siteService.getSite(newTitle);

i++;

} while (siteInfo != null);


shareUtils.createSite(user, MEETING_WORKSPACE_NAME, newTitle, newTitle, "", true);


return newTitle;

}



Creation of the workspace leads to the creation of the site internally.





AlfrescoDwsServiceHandler and AlfrescoCheckOutCheckInServiceHandler these 2 handlers are most important and to be analysed to enable the online edit.




Java code to create the sites in aAlfresco 3.4.5

/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see .
*/
package org.alfresco.module.vti.handler.alfresco.v3;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.alfresco.repo.SessionUser;
import org.alfresco.repo.admin.SysAdminParams;
import org.springframework.extensions.surf.util.URLEncoder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Helper class to work with sites through REST API
*
* @author PavelYur
*/
public class ShareUtils
{
private static Log logger = LogFactory.getLog(ShareUtils.class);

// constants
public static final String HEADER_SET_COOKIE = "Set-Cookie";
public static final String HEADER_CONTENT_TYPE = "Content-Type";
public static final String HEADER_REFERER = "Referer";
public static final String CONTENT_TYPE_JSON = "application/json";
public static final String CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded";
public static final String CONTENT_TYPE_TEXT_PLAIN = "text/plain";
public static final String UTF_8 = "UTF-8";

private SysAdminParams sysAdminParams;

public ShareUtils()
{
}

public void setSysAdminParams(SysAdminParams sysAdminParams)
{
this.sysAdminParams = sysAdminParams;
}

/**
* Get share host with port
*
* @return host where share application is running
*/
public String getShareHostWithPort()
{
return sysAdminParams.getShareProtocol() + "://" + sysAdminParams.getShareHost() + ":" + sysAdminParams.getSharePort();
}

private String getAlfrescoContext()
{
return "/" + sysAdminParams.getAlfrescoContext();
}

private String getAlfrescoHostWithPort()
{
return sysAdminParams.getAlfrescoProtocol() + "://" + sysAdminParams.getAlfrescoHost() + ":" + sysAdminParams.getAlfrescoPort();
}

/**
* Creates new site using REST API, http method is sent to appropriate web script
*
* @param user current user
* @param sitePreset sitePreset for new site
* @param shortName shortName for new site
* @param title title for new site
* @param description description for new site
* @param isPublic is new site public?
* @throws HttpException
* @throws IOException
*/
public void createSite(SessionUser user, String sitePreset, String shortName, String title, String description, boolean isPublic) throws HttpException, IOException
{
HttpClient httpClient = new HttpClient();

String createSiteBody = "{\"isPublic\":\"" + isPublic + "\",\"title\":\"" + title + "\",\"shortName\":\"" + shortName + "\"," + "\"description\":\"" + description
+ "\",\"sitePreset\":\"" + sitePreset + "\"" + (isPublic ? ",\"alfresco-createSite-instance-isPublic-checkbox\":\"on\"}" : "}");
PostMethod createSiteMethod = createPostMethod(getAlfrescoHostWithPort() + getAlfrescoContext() + "/s/api/sites?alf_ticket=" + user.getTicket(), createSiteBody, CONTENT_TYPE_JSON);
try
{
if (logger.isDebugEnabled())
logger.debug("Trying to create site with name: " + shortName + ". URL: " + createSiteMethod.getURI());

int createSiteStatus = httpClient.executeMethod(createSiteMethod);
createSiteMethod.getResponseBody();

if (logger.isDebugEnabled())
logger.debug("Create site method returned status: " + createSiteStatus);
}
catch (Exception e)
{
if (logger.isDebugEnabled())
logger.debug("Fail to create site with name: " + shortName + ". Message: " + e.getMessage());
throw new RuntimeException(e);
}
finally
{
createSiteMethod.releaseConnection();
}

// create title sites component
createComponent(httpClient, shortName, user, "title", "title/collaboration-title");

// create navigation sites component
createComponent(httpClient, shortName, user, "navigation", "navigation/collaboration-navigation");

// create component-1-1 sites component
createComponent(httpClient, shortName, user, "component-1-1", "dashlets/site-welcome");

// create component-1-2 sites component
createComponent(httpClient, shortName, user, "component-1-2", "dashlets/docsummary");

// create component-2-1 sites component
createComponent(httpClient, shortName, user, "component-2-1", "dashlets/site-profile");

// create component-2-2 sites component
createComponent(httpClient, shortName, user, "component-2-2", "dashlets/colleagues");

// create documentLibrary folder
createDocumentLibrary(httpClient, shortName, user);

// create sites dashboard
createSiteDashboard(httpClient, shortName, user, sitePreset);

// If it's a Document WorkSpace, create Links and Data Lists
if ("document-workspace".equalsIgnoreCase(sitePreset))
{
// Create the Links Component
createLinks(httpClient, shortName, user);

// Create the DataLists Component
createDataLists(httpClient, shortName, user);
}
else
{
// Otherwise create the Calendar
createComponent(httpClient, shortName, user, "component-2-3", "dashlets/calendar");
}
}

/**
* Creates site component
*
* @param httpClient HTTP client
* @param siteName name of the site
* @param user current user
* @param componentName name of the component
* @param componentURL URL of the component
* @throws UnsupportedEncodingException
*/
private void createComponent(HttpClient httpClient, String siteName, SessionUser user, String componentName, String componentURL) throws UnsupportedEncodingException
{
String url = getAlfrescoHostWithPort() + getAlfrescoContext() + "/s/remoteadm/create/alfresco/site-data/components/page." + componentName + ".site~" + siteName
+ "~dashboard.xml?s=sitestore&alf_ticket=" + user.getTicket();

String body = "\n" +
"\n" +
"page." + componentName + ".site~" + siteName + "~dashboard\n" +
"page\n" +
"" + componentName + "\n" +
"site/" + siteName + "/dashboard\n" +
"/components/" + componentURL + "\n" +
"
";

PostMethod postMethod = createPostMethod(url, body, "application/octet-stream");
try
{
if (logger.isDebugEnabled())
logger.debug("Trying to create site component with name: " + componentName + ". URL: " + postMethod.getURI());

int status = httpClient.executeMethod(postMethod);
postMethod.getResponseBody();

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();
}
}

/**
* Creates site dashboard
*
* @param httpClient HTTP client
* @param siteName name of the site
* @param user current user
* @throws UnsupportedEncodingException
*/
public void createSiteDashboard(HttpClient httpClient, String siteName, SessionUser user, String sitePreset) throws UnsupportedEncodingException
{
String createSiteDashboardBody = "";
if ("document-workspace".equalsIgnoreCase(sitePreset))
{
createSiteDashboardBody = "\n" +
"\n" +
"Document Workspace Dashboard\n" +
"page.workspace.title\n" +
"Document Workspace dashboard page\n" +
"page.workspace.description\n" +
"dashboard-2-columns-wide-left\n" +
"user\n" +
"\n" +
"[ {\"pageId\":\"documentlibrary\"}, {\"pageId\":\"links\"}," +
" {\"pageId\":\"data-lists\"} ]
\n" +
"
\n" +
"
";
}
else
{
createSiteDashboardBody = "\n" +
"\n" +
"Meeting Workspace Dashboard\n" +
"page.meeting_workspace.title\n" +
"Meeting Workspace dashboard page\n" +
"page.meeting_workspace.description\n" +
"dashboard-2-columns-wide-left\n" +
"user\n" +
"\n" +
"[ " +
"{\"pageId\":\"documentlibrary\"}, {\"pageId\":\"calendar\"} " +
"]
\n" +
"
\n" +
"
";
}

PostMethod createSiteDashboardMethod = createPostMethod(
getAlfrescoHostWithPort() + getAlfrescoContext() + "/s/remoteadm/create/alfresco/site-data/pages/site/" + siteName
+ "/dashboard.xml?s=sitestore&alf_ticket=" + user.getTicket(), 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 (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();
}
}

/**
* Creates documentLibrary folder in site
*
* @param httpClient HTTP client
* @param siteName short name of site
* @param user current user
*/
private void createDocumentLibrary(HttpClient httpClient, String siteName, SessionUser user)
{
GetMethod createDocumentLibraryFolderMethod = createGetMethod(getAlfrescoHostWithPort() + getAlfrescoContext() + "/s/slingshot/doclib/doclist/documents/site/" + siteName
+ "/documentLibrary?filter=recentlyModified&max=10&alf_ticket=" + user.getTicket());
try
{
if (logger.isDebugEnabled())
logger.debug("Trying to create sites documentLibrary folder. URL: " + createDocumentLibraryFolderMethod.getURI());

int status = httpClient.executeMethod(createDocumentLibraryFolderMethod);
createDocumentLibraryFolderMethod.getResponseBody();

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();
}
}

/**
* Creates links folder in site
*
* @param httpClient HTTP client
* @param siteName short name of site
* @param user current user
*/
private void createLinks(HttpClient httpClient, String siteName, SessionUser user)
{
GetMethod createLinksFolderMethod = createGetMethod(
getAlfrescoHostWithPort() + getAlfrescoContext() +
"/s/api/links/site/" + siteName + "/links?page=1&pageSize=1&alf_ticket="
+ user.getTicket());
try
{
if (logger.isDebugEnabled())
logger.debug("Trying to create site links folder. URL: " + createLinksFolderMethod.getURI());

int status = httpClient.executeMethod(createLinksFolderMethod);
createLinksFolderMethod.getResponseBody();

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();
}
}

/**
* Creates the Data Lists folder in site
*
* @param httpClient HTTP client
* @param siteName short name of site
* @param user current user
*/
private void createDataLists(HttpClient httpClient, String siteName, SessionUser user)
{
GetMethod createDataListsFolderMethod = createGetMethod(
getAlfrescoHostWithPort() + getAlfrescoContext() +
"/s/slingshot/datalists/lists/site/" + siteName + "/dataLists?page=1&pageSize=1&alf_ticket="
+ user.getTicket());
try
{
if (logger.isDebugEnabled())
logger.debug("Trying to create site Data Lists folder. URL: " + createDataListsFolderMethod.getURI());

int status = httpClient.executeMethod(createDataListsFolderMethod);
createDataListsFolderMethod.getResponseBody();

if (logger.isDebugEnabled())
logger.debug("Create site Data Lists folder method returned status: " + status);
}
catch (Exception e)
{
if (logger.isDebugEnabled())
logger.debug("Fail to create site Data Lists folder. Message: " + e.getMessage());
throw new RuntimeException(e);
}
finally
{
createDataListsFolderMethod.releaseConnection();
}
}

/**
* 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;
}

/**
* Deletes site using REST API, http method is sent to appropriate web script
*
* @param user current user
* @param shortName shortName of site we are going to delete
* @throws HttpException
* @throws IOException
*/
public void deleteSite(SessionUser user, String shortName) throws HttpException, IOException
{
HttpClient httpClient = new HttpClient();
DeleteMethod deleteSiteMethod = new DeleteMethod(getAlfrescoHostWithPort() + getAlfrescoContext() + "/s/api/sites/" + shortName + "?alf_ticket=" + user.getTicket());
try
{
if (logger.isDebugEnabled())
logger.debug("Trying to delete site with name: " + shortName);

int status = httpClient.executeMethod(deleteSiteMethod);
deleteSiteMethod.getResponseBody();

if (logger.isDebugEnabled())
logger.debug("Delete site method returned status: " + status);
}
catch (Exception e)
{
if (logger.isDebugEnabled())
logger.debug("Fail to delete site with name: " + shortName);
throw new RuntimeException(e);
}
finally
{
deleteSiteMethod.releaseConnection();
}

// deletes site dashboard
deleteSiteDashboard(httpClient, shortName, user);

// deletes title component
deleteSiteComponent(httpClient, shortName, user, "title");

// deletes navigation component
deleteSiteComponent(httpClient, shortName, user, "navigation");

// deletes component-2-2 component
deleteSiteComponent(httpClient, shortName, user, "component-2-2");

// deletes component-1-1 component
deleteSiteComponent(httpClient, shortName, user, "component-1-1");

// deletes component-2-1 component
deleteSiteComponent(httpClient, shortName, user, "component-2-1");

// deletes component-1-2 component
deleteSiteComponent(httpClient, shortName, user, "component-1-2");
}

/**
* Deletes component from site
*
* @param httpClient HTTP client
* @param siteName name of the site
* @param user current user
* @param componentName name of the component
*/
private void deleteSiteComponent(HttpClient httpClient, String siteName, SessionUser user, String componentName)
{
DeleteMethod deleteTitleMethod = new DeleteMethod(getAlfrescoHostWithPort() + getAlfrescoContext() + "/s/remoteadm/delete/alfresco/site-data/components/page." + componentName
+ ".site~" + siteName + "~dashboard.xml?s=sitestore&alf_ticket=" + user.getTicket());
try
{
if (logger.isDebugEnabled())
logger.debug("Trying to delete site component with name: " + siteName);

int status = httpClient.executeMethod(deleteTitleMethod);
deleteTitleMethod.getResponseBody();

if (logger.isDebugEnabled())
logger.debug("Delete site component method returned status: " + status);
}
catch (Exception e)
{
if (logger.isDebugEnabled())
logger.debug("Fail to delete component from site with name: " + siteName);
throw new RuntimeException(e);
}
finally
{
deleteTitleMethod.releaseConnection();
}
}

/**
* Deletes site dashboard
*
* @param httpClient HTTP client
* @param siteName name of the site
* @param user current user
*/
private void deleteSiteDashboard(HttpClient httpClient, String siteName, SessionUser user)
{
DeleteMethod deleteDashboardMethod = new DeleteMethod(getAlfrescoHostWithPort() + getAlfrescoContext() + "/s/remoteadm/delete/alfresco/site-data/pages/site/" + siteName
+ "/dashboard.xml?s=sitestore&alf_ticket=" + user.getTicket());
try
{
if (logger.isDebugEnabled())
logger.debug("Trying to delete dashboard from site with name: " + siteName);

int status = httpClient.executeMethod(deleteDashboardMethod);
deleteDashboardMethod.getResponseBody();

if (logger.isDebugEnabled())
logger.debug("Delete dashboard from site method returned status: " + status);
}
catch (Exception e)
{
if (logger.isDebugEnabled())
logger.debug("Fail to delete dashboard from site with name: " + siteName);
throw new RuntimeException(e);
}
finally
{
deleteDashboardMethod.releaseConnection();
}
}

/**
* Get share context name
*
* @return String share context name
*/
public String getShareContext()
{
return "/" + sysAdminParams.getShareContext();
}

/**
*


* encode string to share specific manner (all characters with code > 127 will be encoded in %u0... format)
*


*
* @param value to encode
* @return encoded value
* @throws UnsupportedEncodingException
*/
public static String encode(String value) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder(value.length());

for (int i = 0; i < value.length(); i++)
{
char c = value.charAt(i);
if (c > 127)
{
result.append("%u0" + Integer.toHexString(c).toUpperCase());
}
else
{
if (c > 'a' && c < 'z' || c > 'A' && c < 'Z' || c == '/' || c == '@' || c == '+')
{
result.append(c);
}
else
{
result.append(URLEncoder.encode(c + ""));
}
}
}
return result.toString();
}
}