Nota del editor: ¿Sabe mucho sobre este tema? ¿Quiere compartir su expertise? Participe hoy mismo en el programa wiki del software IBM Lotus.
| Wiki de Lotus Web Content Management |
|---|
Si trabaja con IBM Lotus Web Content Management, una de sus tareas permanentes será definir la estructura del sitio. Esta tarea, por su misma naturaleza, consume mucho tiempo y es repetitiva; se deben llevar a cabo más de 10 pasos bien diferenciados para crear un solo sitio o un área del sitio. Además, las estructuras de los sitios no son portátiles debido a su diseño; como no puede exportar la estructura del sitio de una biblioteca que se encuentra en un servidor a otra biblioteca ubicada en otro servidor, deberá volver a crearla manualmente.
Como pueden existir miles de sitios y de áreas de los sitios que conforman una única estructura del sitio, es necesario un método para automatizar el proceso de definir la estructura del sitio y facilitar la migración, la exportación y la importación. En este artículo podrá aprender una manera simple de definir la estructura del sitio como archivo XML e implementarla de manera apropiada.
Debe conocer las siguientes tecnologías:
- IBM WebSphere® Portal V6.0 y siguientes: su administración y componentes
- IBM Lotus Web Content Management
- XML
Para demostrar cómo se puede crear una estructura del sitio en Lotus Web Content Management sin crear manualmente todos los sitios y las áreas de los sitios, este artículo utiliza Lotus Web Content Management APIs y un archivo XML que contiene la estructura del sitio. Puede crear el archivo XML que contiene la estructura validándolo con el esquema XML que se encuentra en la sección de Descargas de este artículo. El esquema XML valida la estructura y los campos obligatorios para evitar errores en el tiempo de ejecución.
Puede definir muchos sitios, áreas de los sitios y contenidos predeterminados para crear la estructura del sitio en el documento XML que contiene toda la estructura del sitio. En primer lugar, debe crear los siguientes requisitos previos:
- Biblioteca de Lotus Web Content Management
- Plantillas de autor que se utilizarán en la estructura del sitio
- Plantillas de presentación que se utilizarán en la estructura del sitio
- Usuarios que se utilizarán en la sección security settings (configuraciones de seguridad).
- Flujo de trabajo, acciones durante el flujo de trabajo y etapas del flujo de trabajo que se utilizarán en las plantillas de autor.
Luego defina la estructura del sitio como archivo XML, especificando la biblioteca, los sitios, las áreas de los sitios, etc. Para asegurar que la información que se brinda es suficiente para crear un sitio en Lotus Web Content Management, el archivo XML se basa en el esquema que se define en el archivo XSD que se encuentra en la sección de Descargas de este artículo. El archivo XSD incluye todas las validaciones que se requieren para crear una estructura completa del sitio, con contenidos predeterminados que abarcan algunos campos.
Luego cree un componente JSP para analizar el archivo XML y cree las áreas del sitio que se definen allí.
En esta sección, describimos los pasos que deberá seguir para implementar la solución. Comenzaremos por examinar la creación del archivo XML y el archivo XSD y luego, el componente JSP que analiza este archivo.
El archivo XML contiene toda la información que se necesita para crear la estructura del sitio. Contiene el nombre de la biblioteca, la estructura del sitio, la estructura del área del sitio y los contenidos predeterminados. Es necesario que se defina un archivo XML en una estructura que sea compatible con sus requisitos. Vea el ejemplo de XML del listado 1, que corresponde a la estructura del sitio que se muestra en la figura 1.
Figura 1. Estructura del sitio
El sitio se compone de una única área del sitio; a su vez, esa única área del sitio se compone de otra área del sitio.
Listado 1. Ejemplo de XML utilizado para crear la estructura del sitio.
<Library Name="Library"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="SiteCreation.xsd"> <Site Name="SITE"
DisplayName="SITE"> <SiteArea Name="News" DisplayName="News">
<Settings> <TemplateMapping>
<AuthoringTemp>auth_news</AuthoringTemp>
<PresentationTemp>pt_newsDetail</PresentationTemp>
</TemplateMapping> <SecuritySettings>
<AccessRight Type="addReadAccessMembers"> <Access>[all
authenticated portal users]</Access> <Access>anonymous
portal user</Access> </AccessRight>
</SecuritySettings> </Settings>
<DefaultContent> <Name>Default_News</Name>
<DisplayName>Default_News</DisplayName>
<AuthoringTemp>auth_news</AuthoringTemp>
<TextComponent>
<FieldName>txt_headline</FieldName>
<Value>Headline for default Content</Value>
</TextComponent> <RichTextComponent>
<FieldName>rtf_body</FieldName>
<Value>Body for the default Content</Value>
</RichTextComponent> </DefaultContent> <SiteArea
Name="2009News" DisplayName="2009 News"> <DefaultContent>
<Name>Default_News</Name>
<DisplayName>Default_News</DisplayName>
<AuthoringTemp>auth_news</AuthoringTemp>
<TextComponent>
<FieldName>txt_headline</FieldName>
<Value>Headline for default Content</Value>
</TextComponent> <RichTextComponent>
<FieldName>rtf_body</FieldName>
<Value>Body for the default Content</Value>
</RichTextComponent> </DefaultContent>
</SiteArea> <SiteArea Name="2008News" DisplayName="2008
News"> <DefaultContent>
<Name>Default_News</Name>
</DefaultContent> </SiteArea> </SiteArea>
<Settings><!—Site Settings - <TemplateMapping>
<AuthoringTemp>auth_news</AuthoringTemp>
<PresentationTemp>pt_newsDetail</PresentationTemp>
</TemplateMapping> <SecuritySettings>
<AccessRight Type="addReadAccessMembers"> <Access>[all
authenticated portal users]</Access> <Access>anonymous
portal user</Access> </AccessRight>
</SecuritySettings> </Settings> </Site>
</Library> |
En la Figura 2 se puede ver un mapeo de muestra entre los elementos de XML y los datos de salida creados luego de implementar la solución.
Figura 2. Mapeo entre los objetos y las secciones de XML y Lotus Web Content Management
Como puede ver, el mapeo desde la estructura real del sitio al archivo XML es sencillo y tiene un elemento raíz que representa la biblioteca. Este elemento raíz contiene otro elemento que corresponde al sitio y define su nombre y su nombre para visualización. Las áreas del sitio se definen por anidación en el archivo XML para obtener la estructura del sitio requerida.
Todos los sitios y áreas de los sitios incluyen una sección de configuraciones que contiene las configuraciones de seguridad y las secciones de mapeo de la plantilla. Es necesario tener en cuenta las siguientes restricciones: se pueden crear configuraciones de seguridad y mapeos de la plantilla para cada sitio o área del sitio en su respectivo elemento o en el sitio o el área del sitio más elevado del árbol con sus elementos secundarios que los heredan.
Los flujos de trabajo y las configuraciones de seguridad del contenido se agregan al componente de la plantilla de autor y no a la sección de contenido predeterminado del archivo XML.
Las plantillas de autor y las plantillas de presentación que se utilizan en el mapeo de la plantilla y para crear el contenido predeterminado se deben crear con anterioridad.
El contenido predeterminado se puede reutilizar en múltiples áreas del sitio, definiendo su nombre. Después de que defina un elemento completo de contenido predeterminado en el archivo XML, puede usarlo luego definiendo una etiqueta de contenido predeterminado con el elemento del nombre únicamente. Esta característica de reutilizar el contenido predeterminado en lugares diferentes y múltiples también se puede usar si el contenido predeterminado ya existe para esa biblioteca.
Como ya se mencionó, para evitar la pérdida de los datos que Lotus Web Content Management necesita para crear el sitio, es necesario que usted haga que el archivo XML sea compatible con un XSD. Esto garantiza que las validaciones que se mencionan en la tabla 1 se mantengan para su uso posterior.
Tabla 1. Validaciones de los atributos / elemento del esquema XML
| Elemento | Elemento/atributo | Tipo | Rango válido | Valor |
|---|---|---|---|---|
| Biblioteca | Sitios | Elemento | 0..n | NA |
| Biblioteca | Nombre | Atributo | Obligatorio | cadena |
| Sitio | SiteArea | Elemento | 0..n | NA |
| Sitio | Nombre | Atributo | Obligatorio | cadena |
| Sitio | DisplayName | Atributo | Opcional | cadena |
| Sitio | Configuraciones | Elemento | Opcional | NA |
| SiteArea | SiteArea | Elemento | 0..n | NA |
| SiteArea | Nombre | Atributo | Obligatorio | cadena |
| SiteArea | DisplayName | Atributo | Opcional | cadena |
| SiteArea | Configuraciones | Elemento | Opcional | NA |
| SiteArea | DefaultContent | Elemento | Opcional | NA |
| DefaultContent | Nombre | Elemento | Obligatorio | NA |
| DefaultContent | DisplayName | Elemento | Opcional | NA |
| DefaultContent | AuthoringTemp | Elemento | Opcional (si el elemento se creó antes) | NA |
| DefaultContent | TextComponent | Elemento | 0..n | NA |
| DefaultContent | RichTextComponent | Elemento | Opcional | NA |
| TextComponent | FieldName | Elemento | Obligatorio (referenciación del nombre del campo TextComponent para Lotus Web Content Management como en la plantilla de autor) | NA |
| TextComponent | TextComponent | Elemento | Obligatorio | NA |
| TextComponent | FieldName | Elemento | Obligatorio (referenciación del nombre del campo RichTextComponent para Lotus Web Content Management como en la plantilla de autor) | NA |
| TextComponent | TextComponent | Elemento | Obligatorio | NA |
| Configuraciones | TemplateMapping | Elemento | 0..n | NA |
| Configuraciones | SecuritySettings | Elemento | Opcional | NA |
| TemplateMapping | AuthoringTemp | Elemento | Obligatorio (referencia el nombre de la plantilla de autor Lotus Web Content Management) | NA |
| TemplateMapping | PlantdePresentación | Elemento | Obligatorio (referencia la plantilla de presentación Lotus Web Content Management) | NA |
| SecuritySettings | AccessRight | Elemento | 0..n | NA |
| AccessRight | Tipo | Atributo | Obligatorio | addReadAccessMembers/ ddEditAccessMembers o addDeleteAccessMembers |
| AccessRight | Acceso | Elemento | 1..n | NA |
Ahora que ha definido la estructura del sitio en un archivo XML que es compatible con XSD, es necesario crear un componente JSP para controlar el análisis del archivo XML y llevar a cabo la verdadera creación del sitio Lotus Web Content Management utilizando el Lotus Web Content Management APIs para importar la estructura del sitio a la biblioteca Lotus Web Content Management.
Seleccione New - JSP component (Nuevo - Componente JSP). Cree el componente JSP con el nombre jsp_createSiteStructure y haga que indique un archivo JSP, cuya ruta de acceso sea la siguiente: /jsp/html/createSiteStructure.jsp. Guarde sus componentes JSP en el portlet local de Renderización. La ruta de acceso físico del archivo JSP se encuentra en un directorio que es similar al código que se muestra en el listado 2.
Listado 2. Directorio de la ruta de acceso físico
<websphere portal installation
path>\installedApps\
WCM_Local_ng_Portlet_PA_dvme0nk.ear\PA_dvme0nk.war\jsp\html\
createSiteStructure.jsp |
El archivo JSP crea un botón llamado Create Site Structure (Crear Estructura del Sitio). Al hacer clic, ese botón, comienza a analizar el archivo XML, analizando primero cada sitio. La ruta de acceso al archivo XML se puede editar. Se considera que el archivo utilizado en el listado 3 se encuentra en la misma ubicación que el archivo JSP. El código corresponde al espacio de trabajo y conecta a la biblioteca que se definió en el archivo. Ver el código en el listado 3.
Listado 3. El archivo JSP que crea el nuevo contenido de comentarios
<%@page language="java" contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%> . . . <%@ include
file="wcmUtil.jsp"%> <FORM name="form1" method="post"
action="#"> <INPUT TYPE="HIDDEN" NAME="buttonName"
VALUE="CreateSiteStructure"> <INPUT TYPE="SUBMIT" value="Create Site
Structure"> </FORM> <% try { //if button clicked if(
request.getParameter("buttonName") != null &&
request.getParameter("buttonName").equals("CreateSiteStructure")) { //path to the
XML file containing the site structure File file =
newFile("/opt/app/WebSphere/PortalServer/installedApps/WCM_Local_ng_
Portlet_PA_dm010y1.ear/dm010y1.war/jsp/html/NewsSiteStructure.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder
db = dbf.newDocumentBuilder(); Document doc = db.parse(file);
doc.getDocumentElement().normalize(); Element docEle = doc.getDocumentElement();
String libraryName = docEle.getAttribute("Name"); System.out.println("libraryName =
" +libraryName); workspace = openWorkspaceLibrary(request, libraryName); //retrieve
all site elements NodeList nl = docEle.getElementsByTagName("Site"); //loop over
site elements if(nl != null) { for(int i = 0 ; i < nl.getLength();i++) {
Element el = (Element)nl.item(i); Site site = createSite(el); DocumentId siteId =
site.getId(); System.out.println("site = "+ site.getName()); //for every site
element, retrieve site area child elements NodeList SiteAreaNodeList =
el.getChildNodes(); for (Node node = el.getFirstChild(); node != null; node =
node.getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE
&& node.getNodeName().equals("SiteArea")) { Element siteAreaEL =
(Element)node; SiteArea sa = createSiteArea(siteAreaEL, siteId); if (sa != null){
System.out.println("site area = " + sa.getName()); } else{ out.println("Error in
creation of site area tree, check logs for more information about the error"); } } }
} } closeWorkspace(); out.println("Cretion Completed"); }
}catch(FileNotFoundException e){ out.println("XML File not found!"); }catch
(org.xml.sax.SAXParseException saxEx){ out.println("Exception In parsing document:
"+ saxEx.getMessage()); } catch (Exception e) { System.out.println("Exception: "+
e.getClass()); e.printStackTrace(); } %> |
Se usa una clase de utilidad que contiene todos los métodos auxiliares usados desde el código JSP para crear la estructura del sitio. Con este fin se puede crear un componente JSP llamado wcmUtil.jsp, en el que se encuentren todos estos métodos. El componente JSP se incluye en createSiteStructure.jsp, como se muestra en el listado 3, utilizando el siguiente listado <%@ include file="wcmUtil.jsp"%>.
Los listados 4 - 20 muestran los métodos utilizados en una clase auxiliar para crear la estructura del sitio.
Listado 4. Conectar al espacio de trabajo y a la biblioteca
private Workspace workspace; /* *Connect to Lotus Web
Content Management workspace with current user if *logged in or anonymous if user is
not logged in * *Set the Lotus Web Content Management document library to
aLibraryName */ public Workspace openWorkspaceLibrary(HttpServletRequest request,
String aLibraryName) throws ServiceNotAvailableException, OperationFailedException {
// Connect to WCM Workspace if (request.getUserPrincipal() != null) { workspace =
WCM_API.getRepository().getWorkspace (request.getUserPrincipal()); } else {
workspace = WCM_API.getRepository().getAnonymousWorkspace(); } //set library to the
passed library name if (workspace != null) { DocumentLibrary docLib =
workspace.getDocumentLibrary (aLibraryName); if(docLib != null){
workspace.setCurrentDocumentLibrary(docLib); } } return workspace; } |
Listado 5. Analizar y crear el sitio
/**Parse site element *If site already available,
retrieve the site object, edit the site *If site not already created, create a new
site and set the name and *display name and its settings *Save the site to the
workspace */ public Site createSite(Element aSiteElement){ String siteName =
aSiteElement.getAttribute("Name"); String siteDisplayName =
aSiteElement.getAttribute("DisplayName"); Site site = null; try{ DocumentId siteId =
getWCMDocumentByName(siteName, DocumentTypes.Site); if (siteId != null){ site =
(Site)workspace.getById(siteId); } else{ site = workspace.createSite();
site.setName(siteName); } site.setTitle(siteDisplayName); site =
(Site)retrieveAddSettings(site, aSiteElement, false); workspace.save(site);
}catch(Exception e){ System.out.println("Exception = "+e); e.printStackTrace(); }
return site; } |
Listado 6. Analizar y crear el área del sitio
/**Parse site area element *If site area already
available, retrieve the site area object, edit the site area *If site area not
already created, create a new site area and set the name *and display name and its
settings *Add a default content to the site area if available *Save the site area to
the workspace */ public SiteArea createSiteArea(Element aSiteAreaElement, DocumentId
parentId){ String siteAreaName = aSiteAreaElement.getAttribute("Name"); String
siteAreaDisplayName = aSiteAreaElement.getAttribute("DisplayName"); SiteArea sa =
null; try{ String parentPath = workspace.getPathById(parentId, true, true); String
siteAreaPath = parentPath+ "/"+ siteAreaName; DocumentId siteAreaId =
getWCMDocumentByPath(siteAreaPath, Workspace.WORKFLOWSTATUS_ALL); if (siteAreaId !=
null){ sa = (SiteArea)workspace.getById(siteAreaId); }else{ sa =
workspace.createSiteArea(parentId, null, 1); } sa =
(SiteArea)retrieveAddSettings(sa, aSiteAreaElement, true); if (sa != null){
sa.setTitle(siteAreaDisplayName); sa.setName(siteAreaName); workspace.save(sa); sa =
addDefaultContentToSiteArea(sa, aSiteAreaElement); if (sa != null){ boolean saved =
saveToWorkspace(sa); System.out.println("site area = " + sa.getName()); if (!saved){
return null; } //checking if site area contains any other site area children
NodeList SiteAreaNodeList = aSiteAreaElement.getChildNodes(); for (Node node =
aSiteAreaElement.getFirstChild(); node != null; node = node.getNextSibling()) { if
(node.getNodeType() == Node.ELEMENT_NODE &&
node.getNodeName().equals("SiteArea")) { Element siteAreaEL = (Element)node;
SiteArea childSA = createSiteArea(siteAreaEL, sa.getId()); if (childSA != null){
System.out.println("childSA for = " +sa.getName()+ " = " + childSA.getName()); }
else{ return null; } } } } else{ return null; } } return sa; }catch(Exception e){
System.out.println("Exception = "+e); e.printStackTrace(); } return null; } |
Listado 7. Analizar y crear contenido predeterminado
/**Parse the default content element *If content
already available, retrieve the content object, and edit it *If content not already
created, create a new content object and set the *name and display name and its
settings *If authoring template provided, overwrite if already set *Add text
components and rich text components to the content *Save the default content to the
site area */ public SiteArea addDefaultContentToSiteArea(SiteArea aSiteArea, Element
aSiteAreaElement){ DocumentId defaultContentId = null; Element defaultel =
getChildByName(aSiteAreaElement, "DefaultContent"); String contentName =
getElementValueByTagName("Name", defaultel); defaultContentId =
getWCMDocumentByName(contentName, DocumentTypes.Content); Content content = null;
String contentDisplayName = getElementValueByTagName("DisplayName", defaultel);
String authoringTempName = getElementValueByTagName("AuthoringTemp", defaultel);
DocumentId defaultAuthId = null; if (! authoringTempName.equals("")){ defaultAuthId
= getWCMDocumentByName(authoringTempName, DocumentTypes.AuthoringTemplate); }
System.out.println("defaultAuthId = "+ defaultAuthId); try{ //if content already
existing in the library, re-use it if (defaultContentId != null){ content =
(Content)workspace.getById(defaultContentId); //if authoring template provided in
the file, overwrite the existing one if (defaultAuthId != null){
content.setAuthoringTemplateID(defaultAuthId); } } else if (defaultAuthId != null){
//if content not available, create a new one content =
workspace.createContent(defaultAuthId, aSiteArea.getId(),null, ChildPosition.START);
defaultContentId = content.getId(); content.setName(contentName); } else{
System.out.println("Exception = Authoring Template for default content "+
contentName + " is missing"); return null; } if (! contentDisplayName.equals("")){
content.setTitle(contentDisplayName); } content =
retrieveAddTextComponentToContent(content, defaultel); if (content == null){ return
null; } content = retrieveAddRichTextComponentToContent(content, defaultel); if
(content == null){ return null; } while(!content.isPublished()){
content.nextWorkflowStage(); } workspace.save(content); }catch(Exception e){
System.out.println("Exception = "+e); e.printStackTrace(); }
System.out.println("defaultContent for = " +aSiteArea.getName()+ " = " +
defaultContentId.getName()); aSiteArea.setDefaultContent(defaultContentId); return
aSiteArea; } |
Listado 8. Analizar el componente del texto
/**Parse DefaultContent element *Search for text
component elements *Looping over all text component child elements *Calling method
addTextComponent to add the *text component to the content */ public Content
retriveAddTextComponentToContent(Content aContent, Element aContentElement){
NodeList texttnl = aContentElement.getChildNodes(); for (Node node =
aContentElement.getFirstChild(); node != null; node = node.getNextSibling()) { if
(node.getNodeType() == Node.ELEMENT_NODE &&
node.getNodeName().equals("TextComponent")) { Element textCompel = (Element)node;
String textField = getElementValueByTagName("FieldName", textCompel); String text =
getElementValueByTagName("Value", textCompel); aContent = addTextComponent(aContent,
textField, text); if (aContent != null){ System.out.println("adding textField = "+
textField+" to content " +aContent.getName()); } } } if (aContent == null){ return
null; } else{ return aContent; } } |
Listado 9. Analizar el componente del texto enriquecido
/**Parse DefaultContent element *Search for rich text
component elements *Looping over all rich text component child elements *Calling
method addRichTextComponent to add the rich text *component to the content */ public
Content retrieveAddRichTextComponentToContent (Content aContent, Element
aContentElement){ NodeList richTexttnl = aContentElement.getChildNodes(); for (Node
node = aContentElement.getFirstChild(); node != null; node = node.getNextSibling())
{ if (node.getNodeType() == Node.ELEMENT_NODE &&
node.getNodeName().equals("RichTextComponent")) { Element richtextCompel =
(Element)node; String textField = getElementValueByTagName("FieldName",
richtextCompel); String text = getElementValueByTagName("Value", richtextCompel);
aContent = addRichTextComponent(aContent, textField, text); if (aContent != null){
System.out.println("adding richtextField = "+ textField+" to content "+
aContent.getName()); } } } if (aContent == null){ return null; } else{ return
aContent; } } |
Listado 10. Crear y agregar el componente del texto
/** Get text component from the content according to
*the text component name * Set the text component with the value sent * Add the text
component to the content */ public Content addTextComponent (Content aContent,
String aTextField, String aValue){ try{ TextComponent txtComp = (TextComponent)
aContent.getComponent(aTextField); txtComp.setText(aValue);
aContent.setComponent(aTextField, txtComp); }catch(ComponentNotFoundException ex){
System.out.println ("Exception: "+aTextField+" is not a valid TextComponent");
return null; }catch(Exception e){ System.out.println("Exception = "+e); return null;
} return aContent; } |
Listado 11. Crear y agregar el componente del texto enriquecido
/** Get rich text component from the content according
to the RTF name * Set the rich text component with the value sent * Add the rich
text component to the content */ public Content addRichTextComponent(Content
aContent, String aTextField, String aValue){ try{ RichTextComponent richTxtComp =
(RichTextComponent) aContent.getComponent(aTextField);
richTxtComp.setRichText(aValue); aContent.setComponent(aTextField, richTxtComp);
RichTextComponent rtf = (RichTextComponent)aContent.getComponent(aTextField);
}catch(ComponentNotFoundException ex){ System.out.println("Exception: "+aTextField+"
is not a valid RichTextComponent"); return null; }catch(Exception e){
System.out.println("Exception = "+e); return null; } return aContent; } |
Listado 12. Analizar el elemento de las configuraciones
/**Parse site area or site element *Search for
settings element *call method retrieveAddTemplateMapping to add template mapping to
site or site area *call method addSecuritySettings to add security settings to site
or site area */ public Object retrieveAddSettings(SiteFrameworkContainer aWCMObject,
Element aObjectElement, boolean isSiteArea){ Element settingsel =
getChildByName(aObjectElement, "Settings"); if ( settingsel!= null){ if(isSiteArea )
{ aWCMObject = (SiteArea)retrieveAddTemplateMapping (aWCMObject, settingsel);
aWCMObject = (SiteArea)addSecuritySettings (aWCMObject, settingsel); } else {
aWCMObject = (Site)retrieveAddTemplateMapping (aWCMObject, settingsel); aWCMObject =
(Site)addSecuritySettings (aWCMObject, settingsel); } } return aWCMObject; } |
Listado 13. Agregar SecuritySettings a los objetos de Lotus Web Content Management
/**Parse settings element *Search for SecuritySettings
element *For every SecuritySettings element, find the AccessRight element *loop over
the AccessRight elements and get the type of the access *According to the access
type, a specific method in Lotus *Web Content Management *will be called to add the
access rights */ public Object addSecuritySettings (SiteFrameworkContainer
aWCMObject, Element settingsel){ for (Node node = settingsel.getFirstChild(); node
!= null; node = node.getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE
&& node.getNodeName().equals("SecuritySettings")) { Element secel =
(Element)node; NodeList accessRightsnl = secel.getChildNodes(); for (Node
accessRightNode = secel.getFirstChild(); accessRightNode != null; accessRightNode =
accessRightNode.getNextSibling()) { if (accessRightNode.getNodeType() ==
Node.ELEMENT_NODE &&
accessRightNode.getNodeName().equals("AccessRight")) { Element accessRightsel =
(Element)accessRightNode; String accessType = accessRightsel.getAttribute("Type");
NodeList accessnl = accessRightsel.getChildNodes(); if(accessnl != null ) { for(int
y = 0 ; y < accessnl.getLength();y++) { Node accnode = accessnl.item(y); if
(accnode.getNodeType() == accnode.ELEMENT_NODE &&
accnode.getNodeName().equals("Access")) { Element el = (Element)accnode; String
access = el.getFirstChild().getNodeValue(); if
(accessType.equals("addReadAccessMembers")){ aWCMObject.addReadAccessMembers(new
String[]{access}); System.out.println("addReadAccessMembers for Object =
"+aWCMObject.getName()+" members = "+access); }else if(accessType.equals
("addEditAccessMembers")){ aWCMObject.addEditAccessMembers(new String[]{access});
System.out.println("addEditAccessMembers for Object = "+aWCMObject.getName()+"
members = "+access); }else if(accessType.equals ("addDeleteAccessMembers")){
aWCMObject.addDeleteAccessMembers (new String[]{access}); System.out.println
("addDeleteAccessMembers for Object = "+aWCMObject.getName()+" members = "+access);
} } } } } } } } return aWCMObject; } |
Listado 14. Analizar y agregar TemplateMapping SiteArea
/**Parse settings element *Search for TemplateMapping
element *For every TemplateMapping element *Get the authoring template and
presentation template names *Retrieve the Lotus Web Content Management object from
the names *If item already contains a template mapping with the same authoring
template, *remove it and add the new one *Else, add the new template mapping *Save
the object, either the site or site area */ public Object retrieveAddTemplateMapping
(SiteFrameworkContainer aWCMObject, Element settingsel){ DocumentId authId = null;
DocumentId presId = null; NodeList tempnl = settingsel.getChildNodes(); for (Node
node = settingsel.getFirstChild(); node != null; node = node.getNextSibling()) { if
(node.getNodeType() == Node.ELEMENT_NODE &&
node.getNodeName().equals("TemplateMapping")) { Element tempel = (Element)node;
String authoringTemp = getElementValueByTagName("AuthoringTemp", tempel ); String
presTemp = getElementValueByTagName("PresentationTemp", tempel ); authId =
getWCMDocumentByName(authoringTemp, DocumentTypes.AuthoringTemplate); presId =
getWCMDocumentByName(presTemp, DocumentTypes.PresentationTemplate); if (authId !=
null){ try{ if (aWCMObject.hasTemplateMapping(authId)){ } if
(!aWCMObject.hasTemplateMapping(authId)){ aWCMObject.addTemplateMapping(authId,
presId); } else{ DocumentIdIterator docIt = aWCMObject.getAuthoringTemplateIds(); if
(docIt.hasNext()){ DocumentId dids = (DocumentId)docIt.next();
aWCMObject.removeTemplateMapping(dids); aWCMObject.addTemplateMapping(authId,
presId); } } System.out.println("TemplateMapping authName = "+authoringTemp+" and
presName = "+presTemp +" added to object " + aWCMObject.getName());
workspace.save(aWCMObject); }catch(Exception e){ System.out.println("Exception
="+e); e.printStackTrace(); } }else{ return null; } } } return aWCMObject; } |
Listado 15. Guardar los objetos de Lotus Web Content Management en el espacio de trabajo
/** This is a helper method that receives a Lotus Web
Content Management * document object and adds it to the workspace */ public boolean
saveToWorkspace(com.ibm.workplace.wcm.api.Document wcmDocument){ try{ String[]
errors = workspace.save(wcmDocument); for (int i = 0; i < errors.length;
i++){ System.out.println("Error while saving "+ wcmDocument.getName()+ " :
"+errors[i]); } if (errors.length > 0 ){ return false; } }catch(Exception e){
System.out.println("Exception = "+e); e.printStackTrace(); return false; } return
true; } |
Listado 16. Recuperar los objetos de Lotus Web Content Management por ruta de acceso
/** This is a helper method that retrieves a Lotus Web
Content Management * object by its path and returns the DocumentId */ public
DocumentId getWCMDocumentByPath(String wcmPath, int workFlowStatus) { DocumentId
wcmDocumentId = null; try{ if(wcmPath != null){ DocumentIdIterator docIdIter =
workspace.findByPath(wcmPath, workFlowStatus); if(docIdIter != null
&& docIdIter.hasNext()){ wcmDocumentId = docIdIter.nextId(); } }
}catch(Exception e){ System.out.println("Exception = "+e); e.printStackTrace(); }
return wcmDocumentId; } |
Listado 17. Recuperar el elemento secundario por nombre
/** This is a helper method that gets the child
element according to * its name of another element if * it contains only one child
with that name */ private Element getChildByName(Element element, String name) {
Element rEl = null; for (Node node = element.getFirstChild(); node != null; node =
node.getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE
&& node.getNodeName().equals(name)) { rEl = (Element)node; break; }
} return rEl; } |
Listado 18. Recuperar el valor del elemento por nombre
/** This is a helper method that returns a string
value of the given element */ public String getElementValueByTagName(String
aTagName, Element aElement){ String elementValue = ""; NodeList nodeList =
aElement.getElementsByTagName(aTagName); if(nodeList != null &&
nodeList.getLength() > 0) { Element el = (Element)nodeList.item(0);
elementValue = el.getFirstChild().getNodeValue(); } return elementValue; } |
Listado 19. Recuperar el objeto de Lotus Web Content Management por nombre
/** This is a helper method that returns the
DocumentId of a Lotus Web * Content Management object based on its name */ public
DocumentId getWCMDocumentByName(String wcmName, DocumentType documentTypes){
DocumentId wcmDocumentId = null; try{ if(wcmName != null){ DocumentIdIterator
docIdIter = workspace.findByName(documentTypes, wcmName); if(docIdIter != null
&& docIdIter.hasNext()){ wcmDocumentId = docIdIter.nextId(); } }
}catch(Exception e){ System.out.println("Exception = "+e); e.printStackTrace(); } if
(wcmDocumentId == null && ( (documentTypes.equals
(DocumentTypes.AuthoringTemplate)) || (documentTypes.equals
(DocumentTypes.PresentationTemplate)) )){ System.out.println("Exception: "+wcmName+"
could not be found in the Repository"); } return wcmDocumentId; } |
Listado 20. Cerrar el espacio de trabajo de Lotus Web Content Management
/*** Closes the Lotus Web Content Management workspace
*/ public void closeWorkspace() { WCM_API.getRepository().endWorkspace(); } |
NOTA: El manejo de excepciones se realiza solamente para las ilustraciones y no para el manejo de la calidad de la producción. Se debe modificar si es necesario para cumplir con sus expectativas y requisitos.
La clase auxiliar proporciona algunas advertencias clave:
- Se notifica a los usuarios mediante un mensaje de advertencia que se han producido errores y que no se completó exitosamente la creación.
- En el archivo SystemOut.log hay errores registrados para que usted pueda tener acceso a más información relacionada con errores.
- Los errores que ocurren cuando no se encuentran los usuarios del repositorio producen un error que está registrado, pero también se generan mensajes de Creation Completed (Finalizó la creación) para los usuarios.
Si utiliza la solución propuesta en este artículo, podrá mejorarla. Por ejemplo, puede hacer lo siguiente:
- Crear contenidos utilizando XML
- Agregar componentes más complejos a los contenidos y al contenido predeterminado.
- Cambiar el XML para crear la misma estructura la cantidad de veces que desee, modificando solamente el nombre del área del sitio.
En este artículo, presentamos una solución simple que le permitirá definir las estructuras del sitio de manera automatizada. Los usos de esta solución son muy variados; por ejemplo, puede definir áreas del sitio en varios servidores o es posible que tenga un sitio que contenga una gran cantidad de estructuras del sitio que se repiten. Esta solución le permite ahorrar tiempo en una tarea que, de otro modo, le resultaría monótona y le llevaría demasiado tiempo.
Los autores desean expresar su agradecimiento a Ahmed Abbass, Mourad El-Badry, Raul Munoz Serrano y Tamer El-Mekky, quienes brindaron su tiempo para revisar este artículo y contribuir con sus comentarios.
| Nombre | tamaño | Metodo de descarga |
|---|---|---|
| SiteCreation.xsd | 3628B | HTTP |
| NewsSiteStructure.xml | 1933B | HTTP |
Información sobre métodos de descarga
- Participar en el foro de debate.
- Lea el artículo de developerWorks® Lotus, “End-to-end Web content in WebSphere Portal using Web Content Management 6.0”
(“Contenido Web de extremo a extremo en WebSphere Portal utilizando Web Content
Management 6.0”).
- Lea más en El Centro
de Información de IBM WebSphere Portal Version 6.0.
Hebba Soliman es Senior Software Engineer en el Global Delivery Center de IBM en El Cairo (C-GDC). Tiene amplia experiencia en el desarrollo y diseño de aplicaciones basadas en Internet usando IBM Workplace Web Content Management y personalización.
Ahmed Khairy es IT Specialist en el Technology Development Center de IBM en El Cairo, Egipto. Ha trabajado con varios productos de software de IBM en diferentes marcas de software de IBM. En la actualidad está realizando una Maestría en Ciencias de la Computación en la American University de El Cairo.