Moving to root below branch label

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@2005 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Derek Hulley
2005-12-08 07:13:07 +00:00
commit 3e7141dc1a
225 changed files with 48004 additions and 0 deletions

View File

@@ -0,0 +1,263 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import javax.xml.rpc.ServiceException;
import junit.framework.AssertionFailedError;
import org.alfresco.example.webservice.authentication.AuthenticationResult;
import org.alfresco.example.webservice.authentication.AuthenticationServiceLocator;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSoapBindingStub;
import org.alfresco.example.webservice.content.Content;
import org.alfresco.example.webservice.content.ContentServiceLocator;
import org.alfresco.example.webservice.content.ContentServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.RepositoryServiceLocator;
import org.alfresco.example.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.UpdateResult;
import org.alfresco.example.webservice.types.CML;
import org.alfresco.example.webservice.types.CMLCreate;
import org.alfresco.example.webservice.types.ContentFormat;
import org.alfresco.example.webservice.types.NamedValue;
import org.alfresco.example.webservice.types.ParentReference;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.example.webservice.types.Store;
import org.alfresco.example.webservice.types.StoreEnum;
import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.BaseTest;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Base class for all web service system tests that need to authenticate. The
* setUp method calls the AuthenticationService and authenticates as
* admin/admin, the returned ticket is then stored in
* <code>TicketHolder.ticket</code> so that all subclass implementations can
* use it to call other services.
*
* @see junit.framework.TestCase#setUp()
* @author gavinc
*/
public abstract class BaseWebServiceSystemTest extends BaseTest
{
private static Log logger = LogFactory
.getLog(BaseWebServiceSystemTest.class);
protected static final String USERNAME = "admin";
protected static final String PASSWORD = "admin";
private Properties properties;
private Store store;
private Reference rootNodeReference;
private Reference contentReference;
protected RepositoryServiceSoapBindingStub repositoryService;
protected ContentServiceSoapBindingStub contentService;
public BaseWebServiceSystemTest()
{
try
{
EngineConfiguration config = new FileProvider(getResourcesDir(), "client-deploy.wsdd");
this.contentService = (ContentServiceSoapBindingStub)new ContentServiceLocator(config).getContentService();
assertNotNull(this.contentService);
this.contentService.setTimeout(60000);
this.repositoryService = (RepositoryServiceSoapBindingStub)new RepositoryServiceLocator(config).getRepositoryService();
assertNotNull(this.repositoryService);
this.repositoryService.setTimeout(60000);
}
catch (Exception e)
{
fail("Could not instantiate the content service" + e.toString());
}
}
/**
* Calls the AuthenticationService to retrieve a ticket for all tests to
* use.
*/
@Override
protected void setUp() throws Exception
{
super.setUp();
AuthenticationServiceSoapBindingStub authSvc = null;
try
{
authSvc = (AuthenticationServiceSoapBindingStub) new AuthenticationServiceLocator()
.getAuthenticationService();
} catch (ServiceException jre)
{
if (jre.getLinkedCause() != null)
{
jre.getLinkedCause().printStackTrace();
}
throw new AssertionFailedError("JAX-RPC ServiceException caught: "
+ jre);
}
assertNotNull("authSvc is null", authSvc);
// Time out after a minute
authSvc.setTimeout(60000);
// call the authenticate method and retrieve the ticket
AuthenticationResult result = authSvc.startSession(USERNAME, PASSWORD);
assertNotNull("result is null", result);
String ticket = result.getTicket();
assertNotNull("ticket is null", ticket);
TicketHolder.ticket = ticket;
if (logger.isDebugEnabled())
{
logger.debug("Retrieved and stored ticket: " + TicketHolder.ticket);
}
}
protected Store getStore()
{
if (this.store == null)
{
String strStoreRef = getProperties().getProperty(
WebServiceBootstrapSystemTest.PROP_STORE_REF);
StoreRef storeRef = new StoreRef(strStoreRef);
this.store = new Store(StoreEnum.fromValue(storeRef.getProtocol()),
storeRef.getIdentifier());
}
return this.store;
}
protected Reference getRootNodeReference()
{
if (this.rootNodeReference == null)
{
String strNodeRef = getProperties().getProperty(
WebServiceBootstrapSystemTest.PROP_ROOT_NODE_REF);
NodeRef rootNodeRef = new NodeRef(strNodeRef);
this.rootNodeReference = new Reference(getStore(), rootNodeRef
.getId(), null);
}
return this.rootNodeReference;
}
protected Reference getContentReference()
{
if (this.contentReference == null)
{
String strNodeRef = getProperties().getProperty(WebServiceBootstrapSystemTest.PROP_CONTENT_NODE_REF);
NodeRef nodeRef = new NodeRef(strNodeRef);
this.contentReference = new Reference(getStore(), nodeRef.getId(), null);
}
return this.contentReference;
}
protected ParentReference getFolderParentReference(QName assocName)
{
NodeRef folderNodeRef = getFolderNodeRef();
ParentReference parentReference = new ParentReference();
parentReference.setStore(getStore());
parentReference.setUuid(folderNodeRef.getId());
parentReference.setAssociationType(ContentModel.ASSOC_CONTAINS.toString());
parentReference.setChildName(assocName.toString());
return parentReference;
}
protected Reference createContentAtRoot(String name, String contentValue) throws Exception
{
ParentReference parentRef = new ParentReference();
parentRef.setStore(getStore());
parentRef.setUuid(getRootNodeReference().getUuid());
parentRef.setAssociationType(ContentModel.ASSOC_CHILDREN.toString());
parentRef.setChildName(ContentModel.ASSOC_CHILDREN.toString());
NamedValue[] properties = new NamedValue[]{new NamedValue(ContentModel.PROP_NAME.toString(), name)};
CMLCreate create = new CMLCreate("1", parentRef, ContentModel.TYPE_CONTENT.toString(), properties);
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
UpdateResult[] result = this.repositoryService.update(cml);
Reference newContentNode = result[0].getDestination();
Content content = this.contentService.write(newContentNode, ContentModel.PROP_CONTENT.toString(), contentValue.getBytes(), new ContentFormat("text/plain", "UTF-8"));
assertNotNull(content);
assertNotNull(content.getFormat());
assertEquals("text/plain", content.getFormat().getMimetype());
return content.getNode();
}
/**
* Get the content from the download servlet
*
* @param url
* @return
*/
protected String getContentAsString(String strUrl) throws Exception
{
// Add the ticket to the url
strUrl += "?ticket=" + TicketHolder.ticket;
StringBuilder readContent = new StringBuilder();
URL url = new URL(strUrl);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
int read = is.read();
while (read != -1)
{
readContent.append((char)read);
read = is.read();
}
return readContent.toString();
}
protected Predicate convertToPredicate(Reference reference)
{
Predicate predicate = new Predicate();
predicate.setNodes(new Reference[] {reference});
return predicate;
}
private Properties getProperties()
{
if (this.properties == null)
{
this.properties = WebServiceBootstrapSystemTest
.getBootstrapProperties();
}
return this.properties;
}
private NodeRef getFolderNodeRef()
{
String strNodeRef = getProperties().getProperty(WebServiceBootstrapSystemTest.PROP_FOLDER_NODE_REF);
return new NodeRef(strNodeRef);
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.ws.security.WSPasswordCallback;
/**
* Implements CallbackHandler which returns the currently stored ticket in
* the static <code>ticket</code> field.
*
* @author gavinc
*/
public class TicketHolder implements CallbackHandler
{
public static String ticket;
/**
* @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[])
*/
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
for (int i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof WSPasswordCallback)
{
WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
pc.setPassword(ticket);
}
else
{
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
}
}

View File

@@ -0,0 +1,193 @@
package org.alfresco.example.webservice;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.transaction.UserTransaction;
import junit.framework.TestCase;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.view.ImporterService;
import org.alfresco.service.cmr.view.Location;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sun.corba.se.impl.orb.ParserTable.TestContactInfoListFactory;
public class WebServiceBootstrapSystemTest extends TestCase
{
/**
* NOTE: You need to set the location of the indexes and content store to be a non-realtive
* location in the repository.properties file otherwise running this test here will not
* populate the correct index and content store and the test won't work when running against
* the repository
*/
public static final String FOLDER_NAME = "test folder";
public static final String CONTENT_NAME = "test content";
public static final String PROP_STORE_REF = "storeRef";
public static final String PROP_ROOT_NODE_REF = "rootNodeRef";
public static final String PROP_FOLDER_NODE_REF = "folderNodeRef";
public static final String PROP_CONTENT_NODE_REF = "contentNodeRef";
private static final String TEMP_BOOTSTRAP_PROPERTIES = "./WebServiceTestBootstrap.properties";
private static final String TEST_CONTENT = "This is some test content. This is some test content.";
/**
* Runs the bootstrap and populates the property file with the infomration required for the tests
*/
public void testBootstrap()
{
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:alfresco/application-context.xml");
// Get the services
TransactionService transactionService = (TransactionService)applicationContext.getBean("transactionComponent");
AuthenticationComponent authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent");
NodeService nodeService = (NodeService)applicationContext.getBean("NodeService");
ContentService contentService = (ContentService)applicationContext.getBean("contentService");
ImporterService importerService = (ImporterService)applicationContext.getBean("importerComponent");
UserTransaction userTransaction = transactionService.getUserTransaction();
authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName());
try
{
StoreRef storeRef = null;
NodeRef rootNodeRef = null;
NodeRef folderNodeRef = null;
NodeRef testContent = null;
try
{
userTransaction.begin();
// Create the store
storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
rootNodeRef = rootNodeRef = nodeService.getRootNode(storeRef);
// Import the categories
InputStream viewStream = getClass().getClassLoader().getResourceAsStream("alfresco/bootstrap/categories.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(viewStream));
Location importLocation = new Location(storeRef);
importLocation.setPath("/");
importerService.importView(reader, importLocation, null, null);
// Folder properties
Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(1);
folderProps.put(ContentModel.PROP_NAME, FOLDER_NAME);
// Create a folder
folderNodeRef = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
ContentModel.ASSOC_CHILDREN,
ContentModel.TYPE_FOLDER,
folderProps).getChildRef();
Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(3);
contentProps.put(ContentModel.PROP_NAME, CONTENT_NAME);
// Create some test content
testContent = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
ContentModel.ASSOC_CHILDREN,
ContentModel.TYPE_CONTENT,
contentProps).getChildRef();
ContentWriter writer = contentService.getWriter(testContent, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
writer.setEncoding("UTF-8");
writer.putContent(TEST_CONTENT);
// Add the translatable aspect to the test content
nodeService.addAspect(testContent, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "translatable"), null);
// Create content to be the translation of the translatable content
NodeRef testContent2 = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
ContentModel.ASSOC_CHILDREN,
ContentModel.TYPE_CONTENT,
contentProps).getChildRef();
ContentWriter writer2 = contentService.getWriter(testContent2, ContentModel.PROP_CONTENT, true);
writer2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
writer2.setEncoding("UTF-8");
writer2.putContent(TEST_CONTENT);
// Add the association from the master content to the translated content
nodeService.createAssociation(testContent, testContent2, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "translations"));
userTransaction.commit();
}
catch(Throwable e)
{
// rollback the transaction
try { if (userTransaction != null) {userTransaction.rollback();} } catch (Exception ex) {}
try {authenticationComponent.clearCurrentSecurityContext(); } catch (Exception ex) {}
throw new AlfrescoRuntimeException("Bootstrap failed", e);
}
Properties properties = new Properties();
properties.put(PROP_STORE_REF, storeRef.toString());
properties.put(PROP_ROOT_NODE_REF, rootNodeRef.toString());
properties.put(PROP_FOLDER_NODE_REF, folderNodeRef.toString());
properties.put(PROP_CONTENT_NODE_REF, testContent.toString());
try
{
OutputStream outputStream = new FileOutputStream(TEMP_BOOTSTRAP_PROPERTIES);
properties.store(outputStream, "Web service node store details");
outputStream.flush();
}
catch (Exception e)
{
e.printStackTrace();
fail("Unable to store bootstrap details.");
}
//System.out.println(NodeStoreInspector.dumpNodeStore(nodeService, storeRef));
}
finally
{
authenticationComponent.clearCurrentSecurityContext();
}
}
public static Properties getBootstrapProperties()
{
Properties properties = new Properties();
try
{
InputStream inputStream = new FileInputStream(TEMP_BOOTSTRAP_PROPERTIES);
properties.load(inputStream);
}
catch (Exception e)
{
e.printStackTrace();
fail("Unable to load test bootstrap details. Try running WebServiceBootstrapSystem test, then re-start container and try again.");
}
return properties;
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSystemTest;
import org.alfresco.example.webservice.authoring.AuthoringServiceSystemTest;
import org.alfresco.example.webservice.classification.ClassificationServiceSystemTest;
import org.alfresco.example.webservice.content.ContentServiceSystemTest;
import org.alfresco.example.webservice.repository.RepositoryServiceSystemTest;
import org.alfresco.repo.webservice.CMLUtilTest;
public class WebServiceSuiteSystemTest extends TestSuite
{
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(CMLUtilTest.class);
suite.addTestSuite(AuthenticationServiceSystemTest.class);
suite.addTestSuite(AuthoringServiceSystemTest.class);
suite.addTestSuite(ClassificationServiceSystemTest.class);
suite.addTestSuite(ContentServiceSystemTest.class);
suite.addTestSuite(RepositoryServiceSystemTest.class);
return suite;
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.authentication;
import javax.xml.rpc.ServiceException;
import junit.framework.AssertionFailedError;
import org.alfresco.util.BaseTest;
/**
* Tests the AuthenticationService by trying to login as admin/admin and
* attempting to login with incorrect credentials.
*
* @author gavinc
*/
public class AuthenticationServiceSystemTest extends BaseTest
{
private AuthenticationServiceSoapBindingStub binding;
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception
{
super.setUp();
try
{
this.binding = (AuthenticationServiceSoapBindingStub)new AuthenticationServiceLocator().getAuthenticationService();
}
catch (ServiceException jre)
{
if (jre.getLinkedCause() != null)
{
jre.getLinkedCause().printStackTrace();
}
throw new AssertionFailedError("JAX-RPC ServiceException caught: " + jre);
}
assertNotNull("binding is null", this.binding);
// Time out after a minute
binding.setTimeout(60000);
}
/**
* Tests whether the authentication service is working correctly
*
* @throws Exception
*/
public void testSuccessfulLogin() throws Exception
{
try
{
AuthenticationResult value = this.binding.startSession("admin", "admin");
assertNotNull("result must not be null", value);
System.out.println("ticket = " + value.getTicket());
}
catch (AuthenticationFault error)
{
throw new AssertionFailedError("AuthenticationFault Exception caught: " + error);
}
}
/**
* Tests that a failed authentication attempt fails as expected
*
* @throws Exception
*/
public void testFailedLogin() throws Exception
{
try
{
AuthenticationResult result = this.binding.startSession("wrong", "credentials");
fail("The credentials are incorrect so an AuthenticationFault should have been thrown");
}
catch (AuthenticationFault error)
{
// we expected this
}
}
public void testEndSession() throws Exception
{
this.binding.startSession("admin", "admin");
this.binding.endSession();
}
}

View File

@@ -0,0 +1,371 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.authoring;
import javax.xml.rpc.ServiceException;
import junit.framework.AssertionFailedError;
import org.alfresco.example.webservice.BaseWebServiceSystemTest;
import org.alfresco.example.webservice.content.Content;
import org.alfresco.example.webservice.types.ContentFormat;
import org.alfresco.example.webservice.types.NamedValue;
import org.alfresco.example.webservice.types.ParentReference;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.example.webservice.types.Version;
import org.alfresco.example.webservice.types.VersionHistory;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.namespace.QName;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class AuthoringServiceSystemTest extends BaseWebServiceSystemTest
{
@SuppressWarnings("unused")
private static Log logger = LogFactory.getLog(AuthoringServiceSystemTest.class);
private static final String INITIAL_VERSION_CONTENT = "Content of the initial version";
private static final String SECOND_VERSION_CONTENT = "The content for the second version is completely different";
private static final String VALUE_DESCRIPTION = "description";
private AuthoringServiceSoapBindingStub authoringService;
@Override
protected void setUp() throws Exception
{
super.setUp();
try
{
EngineConfiguration config = new FileProvider(getResourcesDir(),
"client-deploy.wsdd");
this.authoringService = (AuthoringServiceSoapBindingStub) new AuthoringServiceLocator(
config).getAuthoringService();
}
catch (ServiceException jre)
{
if (jre.getLinkedCause() != null)
{
jre.getLinkedCause().printStackTrace();
}
throw new AssertionFailedError("JAX-RPC ServiceException caught: "
+ jre);
}
assertNotNull(this.authoringService);
// Time out after a minute
this.authoringService.setTimeout(60000);
}
/**
* Tests the checkout service method
*
* @throws Exception
*/
public void testCheckout() throws Exception
{
doCheckOut();
// TODO test multiple checkout
}
/**
* Reusable method to do a standard checkout
*
* @return
* @throws Exception
*/
private Reference doCheckOut() throws Exception
{
// Use the helper to create the verionable node
Reference reference = createContentAtRoot("version_test.txt", INITIAL_VERSION_CONTENT);
Predicate predicate = convertToPredicate(reference);
// Check the content out (to the same detination)
CheckoutResult result = this.authoringService.checkout(predicate, null);
assertNotNull(result);
assertEquals(1, result.getOriginals().length);
assertEquals(1, result.getWorkingCopies().length);
// TODO need to check that the working copy and the origional are in the correct states ...
return result.getWorkingCopies()[0];
}
/**
* Tests the checkout service method passing a destination for the working
* copy
*
* @throws Exception
*/
public void testCheckoutWithDestination() throws Exception
{
Reference reference = createContentAtRoot("version_test.txt", INITIAL_VERSION_CONTENT);
Predicate predicate = convertToPredicate(reference);
ParentReference parentReference = getFolderParentReference(QName.createQName("{test}workingCopy"));
// Checkout the content to the folder
CheckoutResult result = this.authoringService.checkout(predicate, parentReference);
assertNotNull(result);
assertEquals(1, result.getOriginals().length);
assertEquals(1, result.getWorkingCopies().length);
// TODO need to check that the working copy and the origional are in the correct states
}
/**
* Tests the checkin service method
*
* @throws Exception
*/
public void testCheckin() throws Exception
{
// First we need to check a document out
Reference workingCopy = doCheckOut();
// Check in but keep checked out
Predicate predicate = convertToPredicate(workingCopy);
NamedValue[] comments = getVersionComments();
CheckinResult checkinResult = this.authoringService.checkin(predicate, comments, true);
// Check the result
assertNotNull(checkinResult);
assertEquals(1, checkinResult.getCheckedIn().length);
assertEquals(1, checkinResult.getWorkingCopies().length);
// TODO check that state of the orig and working copies
// Checkin but don't keep checked out
Predicate predicate2 = convertToPredicate(checkinResult.getWorkingCopies()[0]);
CheckinResult checkinResult2 = this.authoringService.checkin(predicate2, comments, false);
// Check the result
assertNotNull(checkinResult2);
assertEquals(1, checkinResult2.getCheckedIn().length);
assertNull(checkinResult2.getWorkingCopies());
// TODO check the above behaviour ...
// TODO check that the state of the org and working copies
// TODO check multiple checkin
}
/**
* Helper method to get a list of version comments
*
* @return
*/
private NamedValue[] getVersionComments()
{
NamedValue[] comments = new NamedValue[1];
comments[0] = new NamedValue(org.alfresco.service.cmr.version.Version.PROP_DESCRIPTION, VALUE_DESCRIPTION);
return comments;
}
/**
* Tests the checkinExternal service method
*
* @throws Exception
*/
public void testCheckinExternal() throws Exception
{
// First we need to check a document out
Reference workingCopy = doCheckOut();
// Check in with external content
NamedValue[] comments = getVersionComments();
ContentFormat contentFormat = new ContentFormat(MimetypeMap.MIMETYPE_TEXT_PLAIN, "UTF-8");
Reference origionalNode = this.authoringService.checkinExternal(workingCopy, comments, false, contentFormat, SECOND_VERSION_CONTENT.getBytes());
// Check the origianl Node
assertNotNull(origionalNode);
Content[] contents = this.contentService.read(new Predicate(new Reference[]{origionalNode}, getStore(), null), ContentModel.PROP_CONTENT.toString());
Content readResult = contents[0];
assertNotNull(readResult);
String checkedInContent = getContentAsString(readResult.getUrl());
assertNotNull(checkedInContent);
assertEquals(SECOND_VERSION_CONTENT, checkedInContent);
}
/**
* Tests the cancelCheckout service method
*
* @throws Exception
*/
public void testCancelCheckout() throws Exception
{
// Check out a node
Reference workingCopy = doCheckOut();
// Cancel the check out
Predicate predicate = convertToPredicate(workingCopy);
CancelCheckoutResult result = this.authoringService.cancelCheckout(predicate);
// Check the result
assertNotNull(result);
assertEquals(1, result.getOriginals().length);
// TODO check that state of the orig and that the working copy has been deleted
// TODO I don't think that the working copies should be returned in the result since they have been deleted !!
}
/**
* Tests the lock service methods, lock, unlock and getStaus
*
* @throws Exception
*/
public void testLockUnLockGetStatus() throws Exception
{
Reference reference = createContentAtRoot("lock_test1.txt", INITIAL_VERSION_CONTENT);
Predicate predicate = convertToPredicate(reference);
// Get the status
checkLockStatus(predicate, null, null);
// Lock with a write lock
Reference[] lockedRefs = this.authoringService.lock(predicate, false, LockTypeEnum.write);
assertNotNull(lockedRefs);
assertEquals(1, lockedRefs.length);
// TODO check in more detail
// Get the status
checkLockStatus(predicate, USERNAME, LockTypeEnum.write);
// Unlock (bad)
// try
// {
// this.authoringService.unlock(predicate, "bad", false);
// fail("This should have thrown an exception.");
// }
// catch (Throwable exception)
// {
// // Good .. we where expceting this
// }
// Unlock (good)
Reference[] unlocked = this.authoringService.unlock(predicate, false);
assertNotNull(unlocked);
assertEquals(1, unlocked.length);
// Get the status
checkLockStatus(predicate, null, null);
// Read lock
Reference[] lockedRefs2 = this.authoringService.lock(predicate, false, LockTypeEnum.read);
assertNotNull(lockedRefs2);
assertEquals(1, lockedRefs2.length);
// TODO check in more detail
// Get the status
checkLockStatus(predicate, USERNAME, LockTypeEnum.read);
}
private void checkLockStatus(Predicate predicate, String lockOwner, LockTypeEnum lockType)
throws Exception
{
LockStatus[] lockStatus1 = this.authoringService.getLockStatus(predicate);
assertNotNull(lockStatus1);
assertEquals(1, lockStatus1.length);
LockStatus ls1 = lockStatus1[0];
assertNotNull(ls1);
assertEquals(lockOwner, ls1.getLockOwner());
assertEquals(lockType, ls1.getLockType());
}
/**
* Tests the createVersion service method
*
* @throws Exception
*/
public void testVersionMethods() throws Exception
{
Reference reference = createContentAtRoot("create_version_test.txt", INITIAL_VERSION_CONTENT);
Predicate predicate = convertToPredicate(reference);
// Get the version history (before its been versioned)
VersionHistory emptyVersionHistory = this.authoringService.getVersionHistory(reference);
assertNotNull(emptyVersionHistory);
assertNull(emptyVersionHistory.getVersions());
// Create the version
VersionResult result = this.authoringService.createVersion(predicate, getVersionComments(), false);
assertNotNull(result);
assertEquals(1, result.getNodes().length);
assertEquals(1, result.getVersions().length);
Version version = result.getVersions()[0];
assertEquals("1.0", version.getLabel());
// TODO check commentaries
// TODO check creator
// Get the version history
VersionHistory versionHistory = this.authoringService.getVersionHistory(reference);
assertNotNull(versionHistory);
assertEquals(2, versionHistory.getVersions().length);
// TODO some more tests ...
// Update the content
this.contentService.write(reference, ContentModel.PROP_CONTENT.toString(), SECOND_VERSION_CONTENT.getBytes(), null);
// Create another version
VersionResult versionResult2 = this.authoringService.createVersion(predicate, getVersionComments(), false);
assertNotNull(versionResult2);
assertEquals(1, versionResult2.getNodes().length);
assertEquals(1, versionResult2.getVersions().length);
Version version2 = versionResult2.getVersions()[0];
assertEquals("1.3", version2.getLabel());
// TODO check commentaries
// TODO check creator
// Check the version history
VersionHistory versionHistory2 = this.authoringService.getVersionHistory(reference);
assertNotNull(versionHistory2);
assertEquals(4, versionHistory2.getVersions().length);
// TODO some more tests ...
// Confirm the current content of the node
Content[] contents = this.contentService.read(new Predicate(new Reference[]{reference}, getStore(), null), ContentModel.PROP_CONTENT.toString());
Content readResult1 = contents[0];
String content1 = getContentAsString(readResult1.getUrl());
assertEquals(SECOND_VERSION_CONTENT, content1);
// Revert the node to the first version
this.authoringService.revertVersion(reference, "1.0");
// Confirm that the state of the node has been reverted
Content[] contents2 = this.contentService.read(new Predicate(new Reference[]{reference}, getStore(), null), ContentModel.PROP_CONTENT.toString());
Content readResult2 = contents2[0];
String content2 = getContentAsString(readResult2.getUrl());
assertEquals(INITIAL_VERSION_CONTENT, content2);
// Now delete the version history
VersionHistory deletedVersionHistory = this.authoringService.deleteAllVersions(reference);
assertNotNull(deletedVersionHistory);
assertNull(deletedVersionHistory.getVersions());
// Check the version history
VersionHistory versionHistory3 = this.authoringService.getVersionHistory(reference);
assertNotNull(versionHistory3);
assertNull(versionHistory3.getVersions());
}
}

View File

@@ -0,0 +1,199 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.classification;
import javax.xml.rpc.ServiceException;
import junit.framework.AssertionFailedError;
import org.alfresco.example.webservice.BaseWebServiceSystemTest;
import org.alfresco.example.webservice.types.Category;
import org.alfresco.example.webservice.types.ClassDefinition;
import org.alfresco.example.webservice.types.Classification;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.util.GUID;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ClassificationServiceSystemTest extends BaseWebServiceSystemTest
{
private static Log logger = LogFactory
.getLog(ClassificationServiceSystemTest.class);
private ClassificationServiceSoapBindingStub classificationService;
@Override
protected void setUp() throws Exception
{
super.setUp();
try
{
EngineConfiguration config = new FileProvider(getResourcesDir(),
"client-deploy.wsdd");
this.classificationService = (ClassificationServiceSoapBindingStub) new ClassificationServiceLocator(
config).getClassificationService();
} catch (ServiceException jre)
{
if (jre.getLinkedCause() != null)
{
jre.getLinkedCause().printStackTrace();
}
throw new AssertionFailedError("JAX-RPC ServiceException caught: "
+ jre);
}
assertNotNull("contentService is null", this.classificationService);
// Time out after a minute
this.classificationService.setTimeout(60000);
}
/**
* Tests the getClassifications service method
*
* @throws Exception
*/
public void testGetClassifications() throws Exception
{
Classification[] classifications = this.classificationService
.getClassifications(getStore());
assertNotNull(classifications);
assertTrue((classifications.length != 0));
Classification classification = classifications[0];
assertNotNull(classification.getTitle());
assertNotNull(classification.getRootCategory());
assertNotNull(classification.getRootCategory().getId());
assertNotNull(classification.getRootCategory().getTitle());
if (logger.isDebugEnabled() == true)
{
for (Classification item : classifications)
{
logger.debug(
"Classification '" +
item.getTitle() +
"' with root category '" +
item.getRootCategory().getTitle() +
"'");
}
}
}
/**
* Tests the getChildCategories service method
*
* @throws Exception
*/
public void testGetChildCategories() throws Exception
{
Classification[] classifications = this.classificationService.getClassifications(getStore());
Reference parentCategory = classifications[0].getRootCategory().getId();
Category[] categories = this.classificationService.getChildCategories(parentCategory);
assertNotNull(categories);
assertTrue((categories.length != 0));
Category item = categories[0];
assertNotNull(item.getId());
assertNotNull(item.getTitle());
if (logger.isDebugEnabled() == true)
{
for (Category category : categories)
{
logger.debug(
"Sub-category '" +
category.getTitle() +
"'");
}
}
}
/**
* Tests the getCategories and setCategories service methods
*
* @throws Exception
*/
public void testGetAndSetCategories() throws Exception
{
Classification[] classifications = this.classificationService.getClassifications(getStore());
String classification = classifications[0].getClassification();
Reference category = classifications[0].getRootCategory().getId();
Reference reference = createContentAtRoot(GUID.generate(), "Any old content.");
Predicate predicate = convertToPredicate(reference);
// First try and get the categories for a uncategoried node
CategoriesResult[] result1 = this.classificationService.getCategories(predicate);
assertNotNull(result1);
assertEquals(1, result1.length);
assertNull(result1[0].getCategories());
AppliedCategory appliedCategory = new AppliedCategory();
appliedCategory.setCategories(new Reference[]{category});
appliedCategory.setClassification(classification);
AppliedCategory[] appliedCategories = new AppliedCategory[]{appliedCategory};
// Now classify the node
CategoriesResult[] result2 = this.classificationService.setCategories(predicate, appliedCategories);
assertNotNull(result2);
assertEquals(1, result2.length);
// Now get the value back
CategoriesResult[] result3 = this.classificationService.getCategories(predicate);
assertNotNull(result3);
assertEquals(1, result3.length);
CategoriesResult categoryResult = result3[0];
assertEquals(reference.getUuid(), categoryResult.getNode().getUuid());
AppliedCategory[] appCats = categoryResult.getCategories();
assertNotNull(appCats);
assertEquals(1, appCats.length);
AppliedCategory appCat = appCats[0];
assertEquals(classification, appCat.getClassification());
Reference[] refs = appCat.getCategories();
assertNotNull(refs);
assertEquals(1, refs.length);
Reference ref = refs[0];
assertEquals(category.getUuid(), ref.getUuid());
// TODO test multiple classifiations
// TODO test clearing the classifications
// TODO test updating the classifications
}
/**
* Tests the describeClassification service method
*
* @throws Exception
*/
public void testDescribeClassification() throws Exception
{
Classification[] classifications = this.classificationService.getClassifications(getStore());
String classification = classifications[0].getClassification();
ClassDefinition classDefinition = this.classificationService.describeClassification(classification);
assertNotNull(classDefinition);
}
}

View File

@@ -0,0 +1,153 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.content;
import org.alfresco.example.webservice.BaseWebServiceSystemTest;
import org.alfresco.example.webservice.repository.UpdateResult;
import org.alfresco.example.webservice.types.CML;
import org.alfresco.example.webservice.types.CMLCreate;
import org.alfresco.example.webservice.types.ContentFormat;
import org.alfresco.example.webservice.types.NamedValue;
import org.alfresco.example.webservice.types.ParentReference;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ContentServiceSystemTest extends BaseWebServiceSystemTest
{
private static final String CONTENT = "This is a small piece of content to test the create service call";
private static final String UPDATED_CONTENT = "This is some updated content to test the write service call";
private String fileName = "unit-test.txt";
public void testContentService()
throws Exception
{
ParentReference parentRef = new ParentReference();
parentRef.setStore(getStore());
parentRef.setUuid(getRootNodeReference().getUuid());
parentRef.setAssociationType(ContentModel.ASSOC_CHILDREN.toString());
parentRef.setChildName(ContentModel.ASSOC_CHILDREN.toString());
NamedValue[] properties = new NamedValue[]{new NamedValue(ContentModel.PROP_NAME.toString(), this.fileName)};
CMLCreate create = new CMLCreate("1", parentRef, ContentModel.TYPE_CONTENT.toString(), properties);
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
UpdateResult[] result = this.repositoryService.update(cml);
Reference newContentNode = result[0].getDestination();
String property = ContentModel.PROP_CONTENT.toString();
Predicate predicate = new Predicate(new Reference[]{newContentNode}, getStore(), null);
// First check a node that has no content set
Content[] contents1 = this.contentService.read(predicate, property);
assertNotNull(contents1);
assertEquals(1, contents1.length);
Content content1 = contents1[0];
assertNotNull(content1);
assertEquals(0, content1.getLength());
assertEquals(newContentNode.getUuid(), content1.getNode().getUuid());
assertEquals(property, content1.getProperty());
assertNull(content1.getUrl());
assertNull(content1.getFormat());
// Write content
Content content2 = this.contentService.write(newContentNode, property, CONTENT.getBytes(), new ContentFormat(MimetypeMap.MIMETYPE_TEXT_PLAIN, "UTF-8"));
assertNotNull(content2);
assertTrue((content2.getLength() > 0));
assertEquals(newContentNode.getUuid(), content2.getNode().getUuid());
assertEquals(property, content2.getProperty());
assertNotNull(content2.getUrl());
assertNotNull(content2.getFormat());
ContentFormat format2 = content2.getFormat();
assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, format2.getMimetype());
assertEquals("UTF-8", format2.getEncoding());
assertEquals(CONTENT, getContentAsString(content2.getUrl()));
// Read content
Content[] contents3 = this.contentService.read(predicate, property);
assertNotNull(contents3);
assertEquals(1, contents3.length);
Content content3 = contents3[0];
assertNotNull(content3);
assertTrue((content3.getLength() > 0));
assertEquals(newContentNode.getUuid(), content3.getNode().getUuid());
assertEquals(property, content3.getProperty());
assertNotNull(content3.getUrl());
assertNotNull(content3.getFormat());
ContentFormat format3 = content3.getFormat();
assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, format3.getMimetype());
assertEquals("UTF-8", format3.getEncoding());
assertEquals(CONTENT, getContentAsString(content3.getUrl()));
// Update content
Content content4 = this.contentService.write(newContentNode, property, UPDATED_CONTENT.getBytes(), new ContentFormat(MimetypeMap.MIMETYPE_TEXT_CSS, "UTF-8"));
assertNotNull(content4);
assertTrue((content4.getLength() > 0));
assertEquals(newContentNode.getUuid(), content4.getNode().getUuid());
assertEquals(property, content4.getProperty());
assertNotNull(content4.getUrl());
assertNotNull(content4.getFormat());
ContentFormat format4 = content4.getFormat();
assertEquals(MimetypeMap.MIMETYPE_TEXT_CSS, format4.getMimetype());
assertEquals("UTF-8", format4.getEncoding());
assertEquals(UPDATED_CONTENT, getContentAsString(content4.getUrl()));
// Read updated content
Content[] contents5 = this.contentService.read(predicate, property);
assertNotNull(contents5);
assertEquals(1, contents5.length);
Content content5 = contents5[0];
assertNotNull(content5);
assertTrue((content5.getLength() > 0));
assertEquals(newContentNode.getUuid(), content5.getNode().getUuid());
assertEquals(property, content5.getProperty());
assertNotNull(content5.getUrl());
assertNotNull(content5.getFormat());
ContentFormat format5 = content5.getFormat();
assertEquals(MimetypeMap.MIMETYPE_TEXT_CSS, format5.getMimetype());
assertEquals("UTF-8", format5.getEncoding());
assertEquals(UPDATED_CONTENT, getContentAsString(content5.getUrl()));
// Clear content
Content[] contents6 = this.contentService.clear(predicate, property);
assertNotNull(contents6);
assertEquals(1, contents6.length);
Content content6 = contents6[0];
assertNotNull(content6);
assertEquals(0, content6.getLength());
assertEquals(newContentNode.getUuid(), content6.getNode().getUuid());
assertEquals(property, content6.getProperty());
assertNull(content6.getUrl());
assertNull(content6.getFormat());
// Read cleared content
Content[] contents7 = this.contentService.read(predicate, property);
assertNotNull(contents7);
assertEquals(1, contents7.length);
Content content7 = contents7[0];
assertNotNull(content7);
assertEquals(0, content7.getLength());
assertEquals(newContentNode.getUuid(), content7.getNode().getUuid());
assertEquals(property, content7.getProperty());
assertNull(content7.getUrl());
assertNull(content7.getFormat());
}
}

View File

@@ -0,0 +1,535 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.repository;
import javax.xml.rpc.ServiceException;
import junit.framework.AssertionFailedError;
import org.alfresco.example.webservice.BaseWebServiceSystemTest;
import org.alfresco.example.webservice.WebServiceBootstrapSystemTest;
import org.alfresco.example.webservice.types.CML;
import org.alfresco.example.webservice.types.CMLAddAspect;
import org.alfresco.example.webservice.types.CMLCreate;
import org.alfresco.example.webservice.types.ClassDefinition;
import org.alfresco.example.webservice.types.NamedValue;
import org.alfresco.example.webservice.types.Node;
import org.alfresco.example.webservice.types.NodeDefinition;
import org.alfresco.example.webservice.types.ParentReference;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.PropertyDefinition;
import org.alfresco.example.webservice.types.Query;
import org.alfresco.example.webservice.types.QueryConfiguration;
import org.alfresco.example.webservice.types.QueryLanguageEnum;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.example.webservice.types.ResultSet;
import org.alfresco.example.webservice.types.ResultSetRow;
import org.alfresco.example.webservice.types.ResultSetRowNode;
import org.alfresco.example.webservice.types.Store;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class RepositoryServiceSystemTest extends BaseWebServiceSystemTest
{
private static Log logger = LogFactory
.getLog(RepositoryServiceSystemTest.class);
private RepositoryServiceSoapBindingStub repoService;
@Override
protected void setUp() throws Exception
{
super.setUp();
try
{
EngineConfiguration config = new FileProvider(getResourcesDir(),
"client-deploy.wsdd");
this.repoService = (RepositoryServiceSoapBindingStub) new RepositoryServiceLocator(
config).getRepositoryService();
} catch (ServiceException jre)
{
if (jre.getLinkedCause() != null)
{
jre.getLinkedCause().printStackTrace();
}
throw new AssertionFailedError("JAX-RPC ServiceException caught: "
+ jre);
}
assertNotNull("repoService is null", this.repoService);
// Time out after a minute
this.repoService.setTimeout(60000);
}
/**
* Tests the getStores method
*
* @throws Exception
*/
public void testGetStores() throws Exception
{
Store[] stores = this.repoService.getStores();
assertNotNull("Stores array should not be null", stores);
assertTrue("There should be at least 1 store", stores.length >= 1);
}
/**
* Tests the query service call
*
* @throws Exception
*/
public void testQuery() throws Exception
{
// Query query = new Query(QueryLanguageEnum.lucene, "*");
Query query = new Query(QueryLanguageEnum.lucene,
"( +@\\{http\\://www.alfresco.org/1.0\\}name:test*) OR TEXT:test*");
QueryResult queryResult = this.repoService.query(getStore(), query,
false);
assertNotNull("queryResult should not be null", queryResult);
ResultSet resultSet = queryResult.getResultSet();
assertNotNull("The result set should not be null", resultSet);
logger.debug("There are " + resultSet.getTotalRowCount() + " rows:");
if (resultSet.getTotalRowCount() > 0)
{
ResultSetRow[] rows = resultSet.getRows();
for (int x = 0; x < rows.length; x++)
{
ResultSetRow row = rows[x];
NamedValue[] columns = row.getColumns();
for (int y = 0; y < columns.length; y++)
{
logger.debug("row " + x + ": "
+ row.getColumns(y).getName() + " = "
+ row.getColumns(y).getValue());
}
}
} else
{
logger.debug("The query returned no results");
fail("The query returned no results");
}
}
/**
* Tests the ability to retrieve the results of a query in batches
*
* @throws Exception
*/
public void testQuerySession() throws Exception
{
// define a query that will return a lot of hits i.e. EVERYTHING
Query query = new Query(QueryLanguageEnum.lucene, "*");
// add the query configuration header to the call
int batchSize = 5;
QueryConfiguration queryCfg = new QueryConfiguration();
queryCfg.setFetchSize(batchSize);
this.repoService.setHeader(new RepositoryServiceLocator()
.getServiceName().getNamespaceURI(), "QueryHeader", queryCfg);
// get the first set of results back
QueryResult queryResult = this.repoService.query(getStore(), query,
false);
assertNotNull("queryResult should not be null", queryResult);
String querySession = queryResult.getQuerySession();
String origQuerySession = querySession;
assertNotNull("querySession should not be null", querySession);
ResultSet resultSet = queryResult.getResultSet();
assertNotNull("The result set should not be null", resultSet);
logger.debug("There are " + resultSet.getTotalRowCount()
+ " rows in total");
logger.debug("There are " + resultSet.getRows().length
+ " rows in the first set");
assertEquals("The result set size should be " + batchSize, batchSize,
resultSet.getRows().length);
// get the next batch of results
queryResult = this.repoService.fetchMore(querySession);
assertNotNull("queryResult should not be null", queryResult);
querySession = queryResult.getQuerySession();
assertNotNull("querySession should not be null", querySession);
ResultSet resultSet2 = queryResult.getResultSet();
assertNotNull("The second result set should not be null", resultSet2);
logger.debug("There are " + resultSet2.getRows().length
+ " rows in the second set");
assertEquals("The result set size should be " + batchSize, batchSize,
resultSet2.getRows().length);
// get the rest of the results to make sure it finishes properly
while (querySession != null)
{
queryResult = this.repoService.fetchMore(querySession);
assertNotNull("queryResult returned in loop should not be null",
queryResult);
querySession = queryResult.getQuerySession();
logger.debug("There were another "
+ queryResult.getResultSet().getRows().length
+ " rows returned");
}
// try and fetch some more results and we should get an error
try
{
queryResult = this.repoService.fetchMore(origQuerySession);
fail("We should have seen an error as all the results have been returned");
} catch (Exception e)
{
// expected
}
}
/**
* Tests the queryParents service method
*
* @throws Exception
*/
public void testQueryParents() throws Exception
{
// query for all the child nodes of the root
Reference node = getRootNodeReference();
String rootId = node.getUuid();
QueryResult rootChildren = this.repoService.queryChildren(node);
assertNotNull("rootChildren should not be null", rootChildren);
ResultSet rootChildrenResults = rootChildren.getResultSet();
assertNotNull("rootChildrenResults should not be null",
rootChildrenResults);
assertTrue("There should be at least one child of the root node",
rootChildrenResults.getRows().length > 0);
// get hold of the id of the first child
ResultSetRow firstRow = rootChildrenResults.getRows(0);
assertNotNull("getColumns() should not return null", firstRow
.getColumns());
String id = firstRow.getNode().getId();
logger.debug("Retrieving parents for first node found: " + id + "....");
node = new Reference();
node.setStore(getStore());
node.setUuid(id);
QueryResult parents = this.repoService.queryParents(node);
assertNotNull("parents should not be null", parents);
ResultSet parentsResults = parents.getResultSet();
assertNotNull("parentsResults should not be null", parentsResults);
assertTrue("There should be at least one parent", parentsResults
.getRows().length > 0);
// show the results
boolean rootFound = false;
ResultSetRow[] rows = parentsResults.getRows();
for (int x = 0; x < rows.length; x++)
{
ResultSetRow row = rows[x];
assertNotNull("getColumns() should not return null", row
.getColumns());
ResultSetRowNode rowNode = row.getNode();
String nodeId = rowNode.getId();
logger.debug("parent node = " + nodeId + ", type = "
+ rowNode.getType());
if (nodeId.equals(rootId) == true)
{
rootFound = true;
}
}
// make sure the root node was one of the parents
assertTrue("The root node was not found as one of the parents!!",
rootFound);
}
/*
* Tests the queryAssociated service method
*
* @throws Exception
*/
public void testQueryAssociated() throws Exception
{
Reference contentRef = this.getContentReference();
Association association = new Association(QName.createQName(NamespaceService.CONTENT_MODEL_PREFIX, "translations").toString(), AssociationDirectionEnum.target);
QueryResult result = this.repoService.queryAssociated(contentRef, new Association[]{association});
assertNotNull(result);
assertNotNull(result.getResultSet());
assertNotNull(result.getResultSet().getRows());
assertEquals(1, result.getResultSet().getRows().length);
}
/**
* Tests the describe service method
*
* @throws Exception
*/
public void testDescribe() throws Exception
{
// get hold of a node we know some info about so we can test the
// returned values (the Alfresco Tutorial PDF)
Query query = new Query(QueryLanguageEnum.lucene,
"( +@\\{http\\://www.alfresco.org/1.0\\}name:test*) OR TEXT:test*");
QueryResult queryResult = this.repoService.query(getStore(), query,
false);
assertNotNull("queryResult should not be null", queryResult);
ResultSet resultSet = queryResult.getResultSet();
assertNotNull("The result set should not be null", resultSet);
assertTrue("There should be at least one result", resultSet
.getTotalRowCount() > 0);
String id = resultSet.getRows(0).getNode().getId();
assertNotNull("Id of Alfresco Tutorial PDF should not be null", id);
// create a predicate object to to send to describe method
Reference ref = new Reference();
ref.setStore(getStore());
ref.setUuid(id);
Predicate predicate = new Predicate(new Reference[] { ref }, null, null);
// make the service call
NodeDefinition[] nodeDefs = this.repoService.describe(predicate);
assertNotNull("nodeDefs should not be null", nodeDefs);
assertTrue("There should only be one result", nodeDefs.length == 1);
// get the result
NodeDefinition nodeDef = nodeDefs[0];
assertNotNull("The nodeDef should not be null", nodeDef);
ClassDefinition typeDef = nodeDef.getType();
assertNotNull("Type definition should not be null", typeDef);
assertEquals("Type name is incorrect",
"{http://www.alfresco.org/model/content/1.0}content", typeDef
.getName());
assertEquals("Superclass type name is incorrect",
"{http://www.alfresco.org/model/content/1.0}cmobject", typeDef
.getSuperClass());
assertEquals("Type title is incorrect", "Content", typeDef.getTitle());
assertEquals("Type description is incorrect", "Base Content Object", typeDef
.getDescription());
assertFalse("Type is an aspect and it shouldn't be", typeDef
.isIsAspect());
assertNull("There should not be any associations", typeDef
.getAssociations());
assertNotNull("Properties should not be null", typeDef.getProperties());
assertEquals("There should be 2 properties", 2,
typeDef.getProperties().length);
// check the name and type of each of the properties
assertEquals("Property1 name is incorrect",
"{http://www.alfresco.org/model/content/1.0}content", typeDef
.getProperties(0).getName());
assertEquals("Property1 type name is incorrect",
"{http://www.alfresco.org/model/dictionary/1.0}content", typeDef
.getProperties(0).getDataType());
assertEquals("Property5 name is incorrect",
"{http://www.alfresco.org/model/content/1.0}name", typeDef
.getProperties(1).getName());
assertEquals("Property5 type name is incorrect",
"{http://www.alfresco.org/model/dictionary/1.0}text", typeDef
.getProperties(1).getDataType());
// check the aspects
ClassDefinition[] aspects = nodeDef.getAspects();
assertNotNull("aspects should not be null", aspects);
assertEquals("There should be 2 aspects", 2, aspects.length);
// check the first aspect
ClassDefinition aspect1 = aspects[0];
assertEquals("Aspect1 name is incorrect",
"{http://www.alfresco.org/model/system/1.0}referenceable",
aspect1.getName());
assertTrue("Aspect1 should be an aspect", aspect1.isIsAspect());
assertNotNull("Aspect1 should have properties", aspect1.getProperties());
assertEquals("Aspect1 has wrong number of properties", 3, aspect1
.getProperties().length);
// check the second aspect
ClassDefinition aspect2 = aspects[1];
assertEquals("Aspect2 name is incorrect",
"{http://www.alfresco.org/model/content/1.0}auditable", aspect2
.getName());
assertTrue("Aspect2 should be an aspect", aspect2.isIsAspect());
assertNotNull("Aspect2 should have properties", aspect2.getProperties());
assertEquals("Aspect2 has wrong number of properties", 5, aspect2
.getProperties().length);
}
/**
* Tests passing a query in the predicate to return items to describe
*
* @throws Exception
*/
public void testPredicateQuery() throws Exception
{
// define a query to add to the predicate (get everything that mentions
// 'test')
Query query = new Query(QueryLanguageEnum.lucene,
"( +@\\{http\\://www.alfresco.org/1.0\\}name:test*) OR TEXT:test*");
Predicate predicate = new Predicate();
predicate.setQuery(query);
predicate.setStore(getStore());
// call the service and make sure we get some details back
NodeDefinition[] nodeDefs = this.repoService.describe(predicate);
assertNotNull("nodeDefs should not be null", nodeDefs);
assertTrue("There should be at least one result", nodeDefs.length > 0);
NodeDefinition nodeDef = nodeDefs[0];
assertNotNull("The nodeDef should not be null", nodeDef);
ClassDefinition typeDef = nodeDef.getType();
assertNotNull("Type definition should not be null", typeDef);
logger.debug("type name = " + typeDef.getName());
logger.debug("is aspect = " + typeDef.isIsAspect());
PropertyDefinition[] propDefs = typeDef.getProperties();
if (propDefs != null)
{
logger.debug("There are " + propDefs.length + " properties:");
for (int x = 0; x < propDefs.length; x++)
{
PropertyDefinition propDef = propDefs[x];
logger.debug("name = " + propDef.getName() + " type = "
+ propDef.getDataType());
}
}
}
/**
* Tests the use of a path within a reference
*
* @throws Exception
*/
public void testPathReference() throws Exception
{
// setup a predicate to find the test folder using an xpath
Reference ref = new Reference();
ref.setStore(getStore());
ref.setPath("//*[@cm:name = '"
+ WebServiceBootstrapSystemTest.FOLDER_NAME + "']");
Predicate predicate = new Predicate();
predicate.setNodes(new Reference[] { ref });
// call the service and make sure we get some details back
NodeDefinition[] nodeDefs = this.repoService.describe(predicate);
assertNotNull("nodeDefs should not be null", nodeDefs);
assertTrue("There should be at least one result", nodeDefs.length > 0);
NodeDefinition nodeDef = nodeDefs[0];
assertNotNull("The nodeDef should not be null", nodeDef);
ClassDefinition typeDef = nodeDef.getType();
assertNotNull("Type definition should not be null", typeDef);
logger.debug("type name = " + typeDef.getName());
assertEquals("Type is incorrect",
"{http://www.alfresco.org/model/content/1.0}folder", typeDef
.getName());
logger.debug("is aspect = " + typeDef.isIsAspect());
assertFalse("Item should not be an aspect", typeDef.isIsAspect());
PropertyDefinition[] propDefs = typeDef.getProperties();
if (propDefs != null)
{
logger.debug("There are " + propDefs.length + " properties:");
for (int x = 0; x < propDefs.length; x++)
{
PropertyDefinition propDef = propDefs[x];
logger.debug("name = " + propDef.getName() + " type = "
+ propDef.getDataType());
}
}
}
/**
* Tests the update service method
*
* @throws Exception
*/
public void testUpdate() throws Exception
{
CMLCreate create = new CMLCreate();
create.setId("id1");
create.setType(ContentModel.TYPE_CONTENT.toString());
ParentReference parentReference = new ParentReference();
parentReference.setAssociationType(ContentModel.ASSOC_CHILDREN
.toString());
parentReference.setChildName(ContentModel.ASSOC_CHILDREN.toString());
parentReference.setStore(getStore());
parentReference.setUuid(getRootNodeReference().getUuid());
create.setParent(parentReference);
create.setProperty(new NamedValue[] {
new NamedValue(
ContentModel.PROP_NAME.toString(),
"name"),
new NamedValue(
ContentModel.PROP_CONTENT.toString(),
new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, "UTF-8").toString())
});
CMLAddAspect aspect = new CMLAddAspect();
aspect.setAspect(ContentModel.ASPECT_VERSIONABLE.toString());
aspect.setWhere_id("id1");
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
cml.setAddAspect(new CMLAddAspect[]{aspect});
UpdateResult[] results = this.repoService.update(cml);
assertNotNull(results);
assertEquals(2, results.length);
}
public void testGet()
throws Exception
{
Predicate predicate = new Predicate(null, getStore(), null);
Node[] nodes = this.repoService.get(predicate);
assertNotNull(nodes);
assertEquals(1, nodes.length);
Node rootNode = nodes[0];
assertEquals(getRootNodeReference().getUuid(), rootNode.getReference().getUuid());
logger.debug("Root node type = " + rootNode.getType());
String aspects = "";
for (String aspect : rootNode.getAspects())
{
aspects += aspect + ", ";
}
logger.debug("Root node aspects = " + aspects);
for (NamedValue prop : rootNode.getProperties())
{
logger.debug("Root node property " + prop.getName() + " = " + prop.getValue());
}
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.sample;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.xml.rpc.ServiceException;
import org.alfresco.example.webservice.authentication.AuthenticationResult;
import org.alfresco.example.webservice.authentication.AuthenticationServiceLocator;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.RepositoryServiceLocator;
import org.alfresco.example.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.example.webservice.types.Store;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
import org.apache.ws.security.WSPasswordCallback;
/**
* Web service sample 1.
* <p>
* Connect to the reposity and get a list of all the stores available in the repository.
*
* @author Roy Wetherall
*/
public class WebServiceSample1 implements CallbackHandler
{
/** Admin user name and password used to connect to the repository */
public static final String USERNAME = "admin";
public static final String PASSWORD = "admin";
/** The current ticket */
public static String currentTicket;
/** WS security information */
public static final String WS_SECURITY_INFO =
"<deployment xmlns='http://xml.apache.org/axis/wsdd/' xmlns:java='http://xml.apache.org/axis/wsdd/providers/java'>" +
" <transport name='http' pivot='java:org.apache.axis.transport.http.HTTPSender'/>" +
" <globalConfiguration >" +
" <requestFlow >" +
" <handler type='java:org.apache.ws.axis.security.WSDoAllSender' >" +
" <parameter name='action' value='UsernameToken'/>" +
" <parameter name='user' value='ticket'/>" +
" <parameter name='passwordCallbackClass' value='org.alfresco.example.webservice.sample.WebServiceSample1'/>" +
" <parameter name='passwordType' value='PasswordText'/>" +
" </handler>" +
" </requestFlow >" +
" </globalConfiguration>" +
"</deployment>";
/**
* Connect to the respository and print out the names of the available
*
* @param args
*/
public static void main(String[] args)
throws Exception
{
AuthenticationServiceSoapBindingStub authenticationService = (AuthenticationServiceSoapBindingStub)new AuthenticationServiceLocator().getAuthenticationService();
// Start the session
AuthenticationResult result = authenticationService.startSession(WebServiceSample1.USERNAME, WebServiceSample1.PASSWORD);
WebServiceSample1.currentTicket = result.getTicket();
// Get a reference to the respository web service
RepositoryServiceSoapBindingStub repositoryService = getRepositoryWebService();
// Get array of stores available in the repository
Store[] stores = repositoryService.getStores();
if (stores == null)
{
// NOTE: empty array are returned as a null object, this is a issue with the generated web service code.
System.out.println("There are no stores avilable in the repository.");
}
else
{
// Output the names of all the stores available in the repository
System.out.println("The following stores are available in the repository:");
for (Store store : stores)
{
System.out.println(store.getAddress());
}
}
// End the session
authenticationService.endSession();
}
/**
* Get the respository web service.
*
* @return the respository web service
* @throws ServiceException Service Exception
*/
public static RepositoryServiceSoapBindingStub getRepositoryWebService() throws ServiceException
{
// Create the respository service, adding the WS security header information
EngineConfiguration config = new FileProvider(new ByteArrayInputStream(WebServiceSample1.WS_SECURITY_INFO.getBytes()));
RepositoryServiceLocator repositoryServiceLocator = new RepositoryServiceLocator(config);
RepositoryServiceSoapBindingStub repositoryService = (RepositoryServiceSoapBindingStub)repositoryServiceLocator.getRepositoryService();
return repositoryService;
}
/**
* The implementation of the passwrod call back used by the WS Security
*
* @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[])
*/
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
for (int i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof WSPasswordCallback)
{
WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
pc.setPassword(currentTicket);
}
else
{
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
}
}

View File

@@ -0,0 +1,154 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.sample;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import org.alfresco.example.webservice.authentication.AuthenticationResult;
import org.alfresco.example.webservice.authentication.AuthenticationServiceLocator;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.QueryResult;
import org.alfresco.example.webservice.repository.RepositoryFault;
import org.alfresco.example.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.example.webservice.types.NamedValue;
import org.alfresco.example.webservice.types.Query;
import org.alfresco.example.webservice.types.QueryLanguageEnum;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.example.webservice.types.ResultSet;
import org.alfresco.example.webservice.types.ResultSetRow;
import org.alfresco.example.webservice.types.Store;
import org.alfresco.example.webservice.types.StoreEnum;
/**
* Web service sample 2
* <p>
* This sample shows how to execute a search using the repository web service and how to
* query for a nodes parents.
*
* @author Roy Wetherall
*/
public class WebServiceSample2
{
/**
* Main function
*/
public static void main(String[] args)
throws Exception
{
// Get the authentication service
AuthenticationServiceSoapBindingStub authenticationService = (AuthenticationServiceSoapBindingStub)new AuthenticationServiceLocator().getAuthenticationService();
// Start the session
AuthenticationResult result = authenticationService.startSession(WebServiceSample1.USERNAME, WebServiceSample1.PASSWORD);
WebServiceSample1.currentTicket = result.getTicket();
// Execute the search sample
executeSearch();
// End the session
authenticationService.endSession();
}
/**
* Executes a sample query and provides an example of using a parent query.
*
* @return returns a reference to a folder that is the parent of the search results
* ( used in further samples)
* @throws ServiceException Service exception
* @throws RemoteException Remove exception
* @throws RepositoryFault Repository fault
*/
public static Reference executeSearch() throws ServiceException, RemoteException, RepositoryFault
{
Reference parentReference = null;
// Get a reference to the respository web service
RepositoryServiceSoapBindingStub repositoryService = WebServiceSample1.getRepositoryWebService();
// Create a store object referencing the main spaced store
Store store = new Store(StoreEnum.workspace, "SpacesStore");
// Create a query object, looking for all items with alfresco in the name of text
Query query = new Query(QueryLanguageEnum.lucene, "( +@\\{http\\://www.alfresco.org/1.0\\}name:alfresco*) OR TEXT:alfresco*");
// Execute the query
QueryResult queryResult = repositoryService.query(store, query, false);
// Display the results
ResultSet resultSet = queryResult.getResultSet();
ResultSetRow[] rows = resultSet.getRows();
if (rows == null)
{
System.out.println("No query results found.");
}
else
{
System.out.println("Results from query:");
outputResultSet(rows);
// Get the id of the first result
String firstResultId = rows[0].getNode().getId();
Reference reference = new Reference(store, firstResultId, null);
// Get the parent(s) of the first result
QueryResult parentQueryResult = repositoryService.queryParents(reference);
// Get the parent of the first result
ResultSet parentResultSet = parentQueryResult.getResultSet();
ResultSetRow[] parentRows = parentResultSet.getRows();
if (parentRows == null)
{
System.out.println("No query results found.");
}
else
{
System.out.println("Results from parent query:");
outputResultSet(parentRows);
// Return the first parent (we can use in other samples)
String firstParentId = parentRows[0].getNode().getId();
parentReference = new Reference(store, firstParentId, null);
}
}
return parentReference;
}
/**
* Helper method to output the rows contained within a result set
*
* @param rows an array of rows
*/
public static void outputResultSet(ResultSetRow[] rows)
{
for (int x = 0; x < rows.length; x++)
{
ResultSetRow row = rows[x];
NamedValue[] columns = row.getColumns();
for (int y = 0; y < columns.length; y++)
{
System.out.println("row " + x + ": "
+ row.getColumns(y).getName() + " = "
+ row.getColumns(y).getValue());
}
}
}
}

View File

@@ -0,0 +1,185 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.sample;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.rpc.ServiceException;
import org.alfresco.example.webservice.authentication.AuthenticationResult;
import org.alfresco.example.webservice.authentication.AuthenticationServiceLocator;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSoapBindingStub;
import org.alfresco.example.webservice.content.Content;
import org.alfresco.example.webservice.content.ContentServiceLocator;
import org.alfresco.example.webservice.content.ContentServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.UpdateResult;
import org.alfresco.example.webservice.types.CML;
import org.alfresco.example.webservice.types.CMLCreate;
import org.alfresco.example.webservice.types.ContentFormat;
import org.alfresco.example.webservice.types.NamedValue;
import org.alfresco.example.webservice.types.ParentReference;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.example.webservice.types.Store;
import org.alfresco.example.webservice.types.StoreEnum;
import org.alfresco.model.ContentModel;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
/**
* Web service sample 3
* <p>
* This web service sample shows how new content can be added to the repository and how content
* can be read and updated via the web service API.
*
* @author Roy Wetherall
*/
public class WebServiceSample3
{
/** Content strings used in the sample */
private static final String INITIAL_CONTENT = "This is some new content that I am adding to the repository";
private static final String UPDATED_CONTENT = "This is the updated content";
/** The type of the association we are creating to the new content */
private static final String ASSOC_CONTAINS = "{http://www.alfresco.org/model/content/1.0}contains";
/**
* Main function
*/
public static void main(String[] args) throws Exception
{
AuthenticationServiceSoapBindingStub authenticationService = (AuthenticationServiceSoapBindingStub)new AuthenticationServiceLocator().getAuthenticationService();
// Start the session
AuthenticationResult result = authenticationService.startSession(WebServiceSample1.USERNAME, WebServiceSample1.PASSWORD);
WebServiceSample1.currentTicket = result.getTicket();
// Get the content service
ContentServiceSoapBindingStub contentService = getContentWebService();
// Create new content in the respository
Reference newContentReference = createNewContent(contentService, "sampleThreeFileOne.txt", INITIAL_CONTENT);
// Read the newly added content from the respository
Store store = new Store(StoreEnum.workspace, "SpacesStore");
Content[] readResult = contentService.read(
new Predicate(new Reference[]{newContentReference}, store, null),
ContentModel.PROP_CONTENT.toString());
Content content = readResult[0];
// Get the content from the download servlet using the URL and display it
System.out.println("The newly added content is:");
System.out.println(getContentAsString(WebServiceSample1.currentTicket, content.getUrl()));
// Update the content with something new
contentService.write(newContentReference, ContentModel.PROP_CONTENT.toString(), UPDATED_CONTENT.getBytes(), null);
// Now output the updated content
Content[] readResult2 = contentService.read(
new Predicate(new Reference[]{newContentReference}, store, null),
ContentModel.PROP_CONTENT.toString());
Content content2 = readResult2[0];
System.out.println("The updated content is:");
System.out.println(getContentAsString(WebServiceSample1.currentTicket, content2.getUrl()));
// End the session
authenticationService.endSession();
}
/**
* Get the content web service
*
* @return content web service
* @throws ServiceException
*/
public static ContentServiceSoapBindingStub getContentWebService() throws ServiceException
{
// Create the content service, adding the WS security header information
EngineConfiguration config = new FileProvider(new ByteArrayInputStream(WebServiceSample1.WS_SECURITY_INFO.getBytes()));
ContentServiceLocator contentServiceLocator = new ContentServiceLocator(config);
ContentServiceSoapBindingStub contentService = (ContentServiceSoapBindingStub)contentServiceLocator.getContentService();
return contentService;
}
/**
* Helper method to create new content.
*
* @param contentService the content web service
* @param content the content itself
* @return a reference to the created content node
* @throws Exception
*/
public static Reference createNewContent(ContentServiceSoapBindingStub contentService, String name, String contentString)
throws Exception
{
// First we'll use the previous sample to get hold of a reference to a space that we can create the content within
Reference reference = WebServiceSample2.executeSearch();
// Create a parent reference, this contains information about the association we are createing to the new content and the
// parent of the new content (the space retrived from the search)
ParentReference parentReference = new ParentReference(ASSOC_CONTAINS, ASSOC_CONTAINS);
parentReference.setStore(reference.getStore());
parentReference.setUuid(reference.getUuid());
// Define the content format for the content we are adding
ContentFormat contentFormat = new ContentFormat("text/plain", "UTF-8");
NamedValue[] properties = new NamedValue[]{new NamedValue(ContentModel.PROP_NAME.toString(), name)};
CMLCreate create = new CMLCreate("1", parentReference, ContentModel.TYPE_CONTENT.toString(), properties);
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
UpdateResult[] result = WebServiceSample1.getRepositoryWebService().update(cml);
Reference newContentNode = result[0].getDestination();
Content content = contentService.write(newContentNode, ContentModel.PROP_CONTENT.toString(), contentString.getBytes(), contentFormat);
// Get a reference to the newly created content
return content.getNode();
}
/**
* This method gets the content from the download servlet for a given URL and returns it as a string.
*
* @param ticket the current ticket
* @param strUrl the content URL
* @return the content as a string
* @throws Exception
*/
public static String getContentAsString(String ticket, String strUrl) throws Exception
{
// Add the ticket to the url
strUrl += "?ticket=" + ticket;
// Connect to donwload servlet
StringBuilder readContent = new StringBuilder();
URL url = new URL(strUrl);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
int read = is.read();
while (read != -1)
{
readContent.append((char)read);
read = is.read();
}
// return content as a string
return readContent.toString();
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.sample;
import org.alfresco.example.webservice.authentication.AuthenticationResult;
import org.alfresco.example.webservice.authentication.AuthenticationServiceLocator;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.UpdateResult;
import org.alfresco.example.webservice.types.CML;
import org.alfresco.example.webservice.types.CMLAddAspect;
import org.alfresco.example.webservice.types.CMLCreate;
import org.alfresco.example.webservice.types.Node;
import org.alfresco.example.webservice.types.ParentReference;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.example.webservice.types.Store;
import org.alfresco.example.webservice.types.StoreEnum;
import org.alfresco.model.ContentModel;
/**
* Web service sample 4
* <p>
* This sample shows how to construct and execute CML queries using the respository web service.
*
* @author Roy Wetherall
*/
public class WebServiceSample4
{
/**
* Main function
*/
public static void main(String[] args)
throws Exception
{
// Start the session
AuthenticationServiceSoapBindingStub authenticationService = (AuthenticationServiceSoapBindingStub)new AuthenticationServiceLocator().getAuthenticationService();
AuthenticationResult result = authenticationService.startSession(WebServiceSample1.USERNAME, WebServiceSample1.PASSWORD);
WebServiceSample1.currentTicket = result.getTicket();
// Create a store object referencing the main spaced store
Store store = new Store(StoreEnum.workspace, "SpacesStore");
// Get the repository
RepositoryServiceSoapBindingStub repositoryService = WebServiceSample1.getRepositoryWebService();
Reference folder = getTutorialFolder(store, repositoryService);
// Create the CML structure
// When executed this cml update query will create a new content node beneth the tutorial folder and the add the
// versionable aspect to the newly created node
ParentReference parentReference = new ParentReference(ContentModel.ASSOC_CONTAINS.toString(), ContentModel.ASSOC_CONTAINS.toString());
parentReference.setStore(store);
parentReference.setUuid(folder.getUuid());
CMLCreate create = new CMLCreate("id1", parentReference, ContentModel.TYPE_CONTENT.toString(), null);
CMLAddAspect addAspect = new CMLAddAspect(ContentModel.ASPECT_VERSIONABLE.toString(), null, null, "id1");
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
cml.setAddAspect(new CMLAddAspect[]{addAspect});
// Execute the update
UpdateResult[] updateResults = repositoryService.update(cml);
for (UpdateResult updateResult : updateResults)
{
String sourceId = "none";
Reference source = updateResult.getSource();
if (source != null)
{
sourceId = source.getUuid();
}
String destinationId = "none";
Reference destination = updateResult.getDestination();
if (destination != null)
{
destinationId = destination.getUuid();
}
System.out.println(
"Command = " + updateResult.getStatement() +
"; Source = " + sourceId +
"; Destination = " + destinationId);
}
// End the session
authenticationService.endSession();
}
/**
* Get the space immediatly beneth company home call "Alfresco Tutorial"
*
* @param store
* @param repositoryService
* @return
* @throws Exception
*/
public static Reference getTutorialFolder(Store store, RepositoryServiceSoapBindingStub repositoryService)
throws Exception
{
Reference reference = new Reference(store, null, "/app:company_home/*[@cm:name=\"Alfresco Tutorial\"]");
Predicate predicate = new Predicate(new Reference[]{reference}, null, null);
Node[] nodes = repositoryService.get(predicate);
return nodes[0].getReference();
}
}

View File

@@ -0,0 +1,170 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.sample;
import java.io.ByteArrayInputStream;
import javax.xml.rpc.ServiceException;
import org.alfresco.example.webservice.authentication.AuthenticationResult;
import org.alfresco.example.webservice.authentication.AuthenticationServiceLocator;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSoapBindingStub;
import org.alfresco.example.webservice.authoring.AuthoringServiceLocator;
import org.alfresco.example.webservice.authoring.AuthoringServiceSoapBindingStub;
import org.alfresco.example.webservice.authoring.CheckoutResult;
import org.alfresco.example.webservice.content.Content;
import org.alfresco.example.webservice.content.ContentServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.example.webservice.types.CML;
import org.alfresco.example.webservice.types.CMLAddAspect;
import org.alfresco.example.webservice.types.ContentFormat;
import org.alfresco.example.webservice.types.NamedValue;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.example.webservice.types.Store;
import org.alfresco.example.webservice.types.StoreEnum;
import org.alfresco.example.webservice.types.Version;
import org.alfresco.example.webservice.types.VersionHistory;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
/**
* Web service sample 5
* <p>
* This sample shows how to check documents out, check them back in and then view the
* version history.
*
* @author Roy Wetherall
*/
public class WebServiceSample5
{
private final static String INITIAL_CONTENT = "This is the content pror to checkout";
private final static String UPDATED_CONTENT = "This is the updated content";
private final static String VERSIONABLE_ASPECT = "{http://www.alfresco.org/model/content/1.0}versionable";
/**
* Main function
*/
public static void main(String[] args)
throws Exception
{
// Start the session
AuthenticationServiceSoapBindingStub authenticationService = (AuthenticationServiceSoapBindingStub)new AuthenticationServiceLocator().getAuthenticationService();
AuthenticationResult result = authenticationService.startSession(WebServiceSample1.USERNAME, WebServiceSample1.PASSWORD);
WebServiceSample1.currentTicket = result.getTicket();
// Get the content and authoring service
RepositoryServiceSoapBindingStub repositoryService = WebServiceSample1.getRepositoryWebService();
ContentServiceSoapBindingStub contentService = WebServiceSample3.getContentWebService();
AuthoringServiceSoapBindingStub authoringService = WebServiceSample5.getAuthoringWebService();
// Get a reference to a newly created content
Reference contentReference = WebServiceSample3.createNewContent(contentService, "SampleFiveFileOne.txt", INITIAL_CONTENT);
// Add the versionable aspect to the newly created content. This will allows the content to be versioned
makeVersionable(repositoryService, contentReference);
// Checkout the newly created content, placing the working document in the same folder
Predicate itemsToCheckOut = new Predicate(new Reference[]{contentReference}, null, null);
CheckoutResult checkOutResult = authoringService.checkout(itemsToCheckOut, null);
// Get a reference to the working copy
Reference workingCopyReference = checkOutResult.getWorkingCopies()[0];
// Update the content of the working copy
ContentFormat format = new ContentFormat(MimetypeMap.MIMETYPE_TEXT_PLAIN, "UTF-8");
contentService.write(workingCopyReference, ContentModel.PROP_CONTENT.toString(), UPDATED_CONTENT.getBytes(), format);
// Now check the working copy in with a description of the change made that will be recorded in the version history
Predicate predicate = new Predicate(new Reference[]{workingCopyReference}, null, null);
NamedValue[] comments = new NamedValue[]{new NamedValue("description", "The content has been updated")};
authoringService.checkin(predicate, comments, false);
// Output the updated content
Store store = new Store(StoreEnum.workspace, "SpacesStore");
Content[] readResult = contentService.read(
new Predicate(new Reference[]{contentReference}, store, null),
ContentModel.PROP_CONTENT.toString());
Content content = readResult[0];
System.out.println("This is the checked-in content:");
System.out.println(WebServiceSample3.getContentAsString(WebServiceSample1.currentTicket, content.getUrl()));
// Get the version history
System.out.println("The version history:");
VersionHistory versionHistory = authoringService.getVersionHistory(contentReference);
for (Version version : versionHistory.getVersions())
{
// Output the version details
outputVersion(version);
}
// End the session
authenticationService.endSession();
}
/**
* Get a reference to the authoring web service
*
* @return the authoring web service
* @throws ServiceException
*/
public static AuthoringServiceSoapBindingStub getAuthoringWebService() throws ServiceException
{
// Create the content service, adding the WS security header information
EngineConfiguration config = new FileProvider(new ByteArrayInputStream(WebServiceSample1.WS_SECURITY_INFO.getBytes()));
AuthoringServiceLocator authoringServiceLocator = new AuthoringServiceLocator(config);
AuthoringServiceSoapBindingStub authoringService = (AuthoringServiceSoapBindingStub)authoringServiceLocator.getAuthoringService();
return authoringService;
}
/**
* Helper method to make apply the versionable aspect to a given reference
* <p>
* See sample 4 for more CML examples
*
* @param respositoryService the respository service
* @param reference the reference
* @throws Exception
*/
public static void makeVersionable(RepositoryServiceSoapBindingStub respositoryService, Reference reference)
throws Exception
{
// Create the add aspect query object
Predicate predicate = new Predicate(new Reference[]{reference}, null, null);
CMLAddAspect addAspect = new CMLAddAspect(VERSIONABLE_ASPECT, null, predicate, null);
// Create the content management language query
CML cml = new CML();
cml.setAddAspect(new CMLAddAspect[]{addAspect});
// Execute the query, which will add the versionable aspect to the node is question
respositoryService.update(cml);
}
/**
* Helper to output the version details
*
* @param version the version
*/
private static void outputVersion(Version version)
{
System.out.println("Version label = " + version.getLabel() + "; Version description = " + version.getCommentaries()[0].getValue());
}
}

View File

@@ -0,0 +1,139 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.example.webservice.sample;
import java.io.ByteArrayInputStream;
import org.alfresco.example.webservice.authentication.AuthenticationResult;
import org.alfresco.example.webservice.authentication.AuthenticationServiceLocator;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSoapBindingStub;
import org.alfresco.example.webservice.classification.ClassificationServiceLocator;
import org.alfresco.example.webservice.classification.ClassificationServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.QueryResult;
import org.alfresco.example.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.example.webservice.types.Category;
import org.alfresco.example.webservice.types.Classification;
import org.alfresco.example.webservice.types.Query;
import org.alfresco.example.webservice.types.QueryLanguageEnum;
import org.alfresco.example.webservice.types.Store;
import org.alfresco.example.webservice.types.StoreEnum;
import org.alfresco.repo.search.ISO9075;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
/**
* Web service sample 6
* <p>
* Example showing how content can be queried for using categories
*
* @author Roy Wetherall
*/
public class WebServiceSample6
{
/**
* Main function
*/
public static void main(String[] args)
throws Exception
{
// Start the session
AuthenticationServiceSoapBindingStub authenticationService = (AuthenticationServiceSoapBindingStub)new AuthenticationServiceLocator().getAuthenticationService();
AuthenticationResult result = authenticationService.startSession(WebServiceSample1.USERNAME, WebServiceSample1.PASSWORD);
WebServiceSample1.currentTicket = result.getTicket();
// Get the content and authoring service
RepositoryServiceSoapBindingStub repositoryService = WebServiceSample1.getRepositoryWebService();
// Get the classification service
EngineConfiguration config = new FileProvider(new ByteArrayInputStream(WebServiceSample1.WS_SECURITY_INFO.getBytes()));
ClassificationServiceSoapBindingStub classificationService = (ClassificationServiceSoapBindingStub) new ClassificationServiceLocator(config).getClassificationService();
// Create the store reference
Store store = new Store(StoreEnum.workspace, "SpacesStore");
// Get all the classifications
Classification[] classifications = classificationService.getClassifications(store);
// Output some details
System.out.println("All classifications:");
for (Classification classification : classifications)
{
System.out.println(classification.getClassification());
System.out.println("Classification = " + classification.getTitle() + "; Root category = " + classification.getRootCategory().getTitle());
}
// Get the class definition for the classification we are interested in
Classification classification = classifications[0];
// Get the child categories
Category[] categories = null;
if (classifications.length > 0)
{
categories = classificationService.getChildCategories(classifications[0].getRootCategory().getId());
if (categories != null)
{
// Output some details
System.out.println("The child categories of classification '" + classifications[0].getTitle() + "':");
for (Category category : categories)
{
System.out.println("Title = " + category.getTitle());
}
}
else
{
System.out.println("No child categories found.");
}
}
// Now build a path query
StringBuilder pathQuery = new StringBuilder(128);
//pathQuery.append("PATH:\"cm:generalclassifiable/cm:MyTestCategory/cm:One/member\"");
// Encode the root category name
String encodedRoot = ISO9075.encode(classification.getRootCategory().getTitle());
// Build up the search path
if (categories != null && categories.length != 0)
{
for (int i=0; i<categories.length; i++)
{
if (pathQuery.length() != 0)
{
pathQuery.append("OR");
}
String encoded = ISO9075.encode(categories[i].getTitle());
pathQuery.append(" PATH:\"cm:generalclassifiable/cm:" + encodedRoot + "/cm:" + encoded + "/member\" ");
}
}
System.out.println("Query path: " + pathQuery.toString());
// Call the repository service to do search based on category
Query query = new Query(QueryLanguageEnum.lucene, pathQuery.toString());
// Execute the query
QueryResult queryResult = repositoryService.query(store, query, true);
System.out.println("Category query results:");
WebServiceSample2.outputResultSet(queryResult.getResultSet().getRows());
// End the session
authenticationService.endSession();
}
}

View File

@@ -0,0 +1,263 @@
// NOTE: if you change the package location of this class you will need to update the WS_SEURITY_INFO XML as for this example this class
// doubles as the passwordCAllbackClass
package org.alfresco.example.webservice.sample;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.example.webservice.authentication.AuthenticationResult;
import org.alfresco.example.webservice.authentication.AuthenticationServiceLocator;
import org.alfresco.example.webservice.authentication.AuthenticationServiceSoapBindingStub;
import org.alfresco.example.webservice.repository.QueryResult;
import org.alfresco.example.webservice.repository.RepositoryServiceLocator;
import org.alfresco.example.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.example.webservice.types.NamedValue;
import org.alfresco.example.webservice.types.Node;
import org.alfresco.example.webservice.types.Predicate;
import org.alfresco.example.webservice.types.Query;
import org.alfresco.example.webservice.types.QueryLanguageEnum;
import org.alfresco.example.webservice.types.Reference;
import org.alfresco.example.webservice.types.ResultSet;
import org.alfresco.example.webservice.types.ResultSetRow;
import org.alfresco.example.webservice.types.Store;
import org.alfresco.example.webservice.types.StoreEnum;
import org.alfresco.model.ContentModel;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.configuration.FileProvider;
import org.apache.ws.security.WSPasswordCallback;
public class WebServiceSampleGetRankedContent implements CallbackHandler
{
/** Admin user name and password used to connect to the repository */
public static final String USERNAME = "admin";
public static final String PASSWORD = "admin";
/** The current ticket */
public static String currentTicket;
/** WS security information */
public static final String WS_SECURITY_INFO =
"<deployment xmlns='http://xml.apache.org/axis/wsdd/' xmlns:java='http://xml.apache.org/axis/wsdd/providers/java'>" +
" <transport name='http' pivot='java:org.apache.axis.transport.http.HTTPSender'/>" +
" <globalConfiguration >" +
" <requestFlow >" +
" <handler type='java:org.apache.ws.axis.security.WSDoAllSender' >" +
" <parameter name='action' value='UsernameToken'/>" +
" <parameter name='user' value='ticket'/>" +
" <parameter name='passwordCallbackClass' value='org.alfresco.example.webservice.sample.WebServiceSampleGetRankedContent'/>" +
" <parameter name='passwordType' value='PasswordText'/>" +
" </handler>" +
" </requestFlow >" +
" </globalConfiguration>" +
"</deployment>";
/**
* Main method
*
* @param args
*/
public static void main(String[] args)
{
WebServiceSampleGetRankedContent sample = new WebServiceSampleGetRankedContent();
List<ContentResult> results = sample.getRankedContent("Alfresco Tutorial", "alfresco*");
// Output the results for visual inspection
int iCount = 1;
for (ContentResult result : results)
{
System.out.println("Result " + iCount + ": " + result.toString());
iCount ++;
}
}
/**
* Get a list of ordered results of documents in the space specified matching the search
* text provided.
*
* @param spaceName the name of the space (immediatly beneth the company home space) to search
* @param searchValue the FTS search value
* @return list of results
*/
public List<ContentResult> getRankedContent(String spaceName, String searchValue)
{
List<ContentResult> results = new ArrayList<ContentResult>();
try
{
// Get the authentication service
AuthenticationServiceSoapBindingStub authenticationService = (AuthenticationServiceSoapBindingStub)new AuthenticationServiceLocator().getAuthenticationService();
// Start the session
AuthenticationResult authenticationResult = authenticationService.startSession(WebServiceSample1.USERNAME, WebServiceSample1.PASSWORD);
WebServiceSampleGetRankedContent.currentTicket = authenticationResult.getTicket();
// Create the respository service, adding the WS security header information
EngineConfiguration config = new FileProvider(new ByteArrayInputStream(WebServiceSampleGetRankedContent.WS_SECURITY_INFO.getBytes()));
RepositoryServiceLocator repositoryServiceLocator = new RepositoryServiceLocator(config);
RepositoryServiceSoapBindingStub repositoryService = (RepositoryServiceSoapBindingStub)repositoryServiceLocator.getRepositoryService();
// Create a store object referencing the main spaced store
Store store = new Store(StoreEnum.workspace, "SpacesStore");
// Get a reference to the space we have named
Reference reference = new Reference(store, null, "/app:company_home/*[@cm:name=\"" + spaceName + "\"]");
Predicate predicate = new Predicate(new Reference[]{reference}, null, null);
Node[] nodes = repositoryService.get(predicate);
// Create a query object, looking for all items with alfresco in the name of text
Query query = new Query(
QueryLanguageEnum.lucene,
"+PARENT:\"workspace://SpacesStore/"+ nodes[0].getReference().getUuid() + "\" +TEXT:\"" + searchValue + "\"");
// Execute the query
QueryResult queryResult = repositoryService.query(store, query, false);
// Display the results
ResultSet resultSet = queryResult.getResultSet();
ResultSetRow[] rows = resultSet.getRows();
if (rows != null)
{
// Get the infomation from the result set
for(ResultSetRow row : rows)
{
String nodeId = row.getNode().getId();
ContentResult contentResult = new ContentResult(nodeId);
for (NamedValue namedValue : row.getColumns())
{
if (namedValue.getName().endsWith(ContentModel.PROP_CREATED.toString()) == true)
{
contentResult.setCreateDate(namedValue.getValue());
}
else if (namedValue.getName().endsWith(ContentModel.PROP_NAME.toString()) == true)
{
contentResult.setName(namedValue.getValue());
}
else if (namedValue.getName().endsWith(ContentModel.PROP_DESCRIPTION.toString()) == true)
{
contentResult.setDescription(namedValue.getValue());
}
else if (namedValue.getName().endsWith(ContentModel.PROP_CONTENT.toString()) == true)
{
// We could go to the content service and ask for the content to get the URL but to save time we
// might as well dig the content URL out of the results.
String contentString = namedValue.getValue();
String[] values = contentString.split("[|=]");
contentResult.setUrl(values[1]);
}
}
results.add(contentResult);
}
}
// End the session
authenticationService.endSession();
}
catch (Exception serviceException)
{
throw new AlfrescoRuntimeException("Unable to perform search.", serviceException);
}
return results;
}
/**
* Security callback handler
*/
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
for (int i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof WSPasswordCallback)
{
WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
pc.setPassword(WebServiceSampleGetRankedContent.currentTicket);
}
else
{
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
}
/**
* Class to contain the information about the result from the query
*/
public class ContentResult
{
private String id;
private String name;
private String description;
private String url;
private String createDate;
public ContentResult(String id)
{
this.id = id;
}
public String getCreateDate()
{
return createDate;
}
public void setCreateDate(String createDate)
{
this.createDate = createDate;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
@Override
public String toString()
{
return "id=" + this.id +
"; name=" + this.name +
"; description=" + this.description +
"; created=" + this.createDate +
"; url=" + this.url;
}
}
}