Skip to Content

Recently, Daniel Wroblewski published a blog about uploading portal content and actions through XML files. See it SP15: XML Content and Actions. I have built a portal component that makes use of this capability through client side eventing to allow for creation of PCD folders with a predefined set of content.

Why do we need this? During some SAP training we can generate a set of PCD folders for multiple groups of students. Each student group gets subfolders for iViews, pages, roles etc, and we build a role structure for each student with a predefined entry point.

The component prompts for a top level folder name, how many groups to create and what prefix to use for folders and objects.

image

These values are obtained from the portal properties defined in portalapp.xml as below:

When it finishes, you end up with a PCD similar to:

image

The portal component is implemented with the following code:

package com.sap.anz;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import com.sapportals.htmlb.Button;
import com.sapportals.htmlb.Form;
import com.sapportals.htmlb.GridLayout;
import com.sapportals.htmlb.Group;
import com.sapportals.htmlb.InputField;
import com.sapportals.htmlb.Label;
import com.sapportals.htmlb.MessageBar;
import com.sapportals.htmlb.enum.ButtonDesign;
import com.sapportals.htmlb.enum.DataType;

import com.sapportals.htmlb.enum.GroupDesign;
import com.sapportals.htmlb.enum.MessageType;
import com.sapportals.htmlb.event.Event;
import com.sapportals.htmlb.page.DynPage;
import com.sapportals.htmlb.page.PageException;
import com.sapportals.htmlb.page.PageProcessor;
import com.sapportals.portal.htmlb.page.PageProcessorComponent;
import com.sapportals.portal.prt.component.IPortalComponentProfile;
import com.sapportals.portal.prt.component.IPortalComponentRequest;
import com.sapportals.portal.prt.component.IPortalComponentResponse;
import com.sapportals.portal.prt.pom.IEvent;

public class Creation extends PageProcessorComponent
{
public class CreationDynPage extends DynPage
{

public void doInitialization()
throws PageException
{
executeEnabled = true;
latestMessage = "";
latestStatus = MessageType.NONE;
}

public void doProcessAfterInput()
throws PageException
{
}

public void doProcessBeforeOutput()
throws PageException
{
m_response = (IPortalComponentResponse)getResponse();
m_request = (IPortalComponentRequest)getRequest();
if(m_response == null)
{
try
{
uploadContent();
}
catch(Exception e)
{
}
return;
} else
{
String parentFolder = "";
String defaultPrefix = "";
String defaultFolderPrefix = "";
try {
IPortalComponentProfile profile = m_request.getComponentContext().getProfile();
parentFolder = profile.getProperty("ParentFolder");
defaultPrefix = profile.getProperty("Prefix");
defaultFolderPrefix = profile.getProperty("FolderPrefix");
}
catch
(Exception e) {
latestMessage = e.getLocalizedMessage();
latestStatus = MessageType.ERROR;
}
getUserName(parentFolder, defaultPrefix, defaultFolderPrefix);
return;
}
}

public void doExecute(Event evt)
{
executeEnabled = false;
}

private void getUserName(String defaultParentFolder, String defaultPrefix, String defaultFolderPrefix)
{
Form frm = getForm();
int col = 1;
int row = 1;

GridLayout descGrid = new GridLayout();
int row_grid1 = 1;
int col_grid1 = 1;
Group myGroup = new Group();
myGroup.setWidth("350");
myGroup.setTitle("PCD folder creation");
myGroup.setDesign(GroupDesign.SAPCOLOR);
frm.addComponent(myGroup);

GridLayout gl = new GridLayout();
gl.setCellPadding(5);
myGroup.addComponent(gl);

InputField userName = new InputField("Username");
Label label = new Label("Groups");
userName.setLabel(label);
userName.setTooltip("Number of user groups to create folders for");
userName.setString("10");
userName.setWidth("20");
userName.setType(DataType.INTEGER);
gl.addComponent(row_grid1, col_grid1, label);
gl.addComponent(row_grid1, col_grid1+1, userName);

row_grid1++;
InputField topFolder = new InputField("TopFolder");
topFolder.setString(defaultParentFolder);
topFolder.setTooltip("Folder in PCD under portal_content where folders will be generated");
label = new Label("Under PCD folder");
topFolder.setLabel(label);
gl.addComponent(row_grid1, col_grid1, label);
gl.addComponent(row_grid1, col_grid1+1, topFolder);

row_grid1++;
InputField prefix = new InputField("Prefix");
prefix.setString(defaultPrefix);
label = new Label("Prefix for objects");
prefix.setLabel(label);
gl.addComponent(row_grid1, col_grid1, label);
gl.addComponent(row_grid1, col_grid1+1, prefix);

row_grid1++;
InputField folderPrefix = new InputField("folderPrefix");
folderPrefix.setString(defaultFolderPrefix);
label = new Label("Prefix for folders");
folderPrefix.setLabel(label);
gl.addComponent(row_grid1, col_grid1, label);
gl.addComponent(row_grid1, col_grid1+1, folderPrefix);

row_grid1++;

MessageBar usefulBar = new MessageBar("usefulBar");
usefulBar.setMessageType(latestStatus);
usefulBar.setMessageText(latestMessage);
row_grid1++;
gl.addComponent(row_grid1, col_grid1, usefulBar);

row_grid1++;
Button btnExecute = new Button("btnExecute");
btnExecute.setText("Start");
btnExecute.setOnClientClick("showLoad()");
btnExecute.setOnClick("doExecute");
btnExecute.setOKButton(true);
btnExecute.setDesign(ButtonDesign.EMPHASIZED);
gl.addComponent(row_grid1, col_grid1, btnExecute);

MessageBar exeBar = new MessageBar("exeBar");
exeBar.setMessage(MessageType.LOADING, "loading...");
frm.addRawText("

");
frm.addRawText("

“);

               frm.setDefaultButton(btnExecute);

          }

          private void uploadContent()

          {

               IPortalComponentProfile profile = m_request.getComponentContext().getProfile();

               String userName = ((InputField)getComponentByName(“Username”)).getValue().toString();

               String topFolder = ((InputField)getComponentByName(“TopFolder”)).getValue().toString();

               String prefix = ((InputField)getComponentByName(“Prefix”)).getValue().toString();

               String folderPrefix = ((InputField)getComponentByName(“folderPrefix”)).getValue().toString();

               String generatedFile = profile.getProperty(“GeneratedFile”);

               String origFileName = generatedFile;

               m_request.putValue(“originFile”, origFileName);

               if (topFolder.equals(“”) || userName.equals(“”)) {

                    latestMessage = “Please enter a number of groups and a top level PCD folder”;

                    latestStatus = MessageType.WARNING;

               return;

          }

               try

               {

                    Object user = m_request.getUser();

                    File genFile = new File(generatedFile);

                    BufferedWriter o1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(genFile), “UTF8”));

                    o1.write(GenericCreatorTag());

                    Integer Count = new Integer(userName);

                    int count = Count.intValue();

                    for (int i = 0; i <= count; i++) {

                         userName = (new Integer(i) ).toString();

                         if (i < 10) userName = “0”+userName;

                         if (i == 0) {

                              o1.write(ContextTag(topFolder, “”, “portal_content”, “”));

                         };

                         o1.write(ContextTag(userName, “Group”, “portal_content/”+topFolder, folderPrefix));

                         o1.write(ContextTag(“iViews”, “Group “userName, “portal_content/”topFolder“/”folderPrefix+userName, folderPrefix));

                         o1.write(ContextTag(“Pages”, “Group “userName, “portal_content/”topFolder“/”folderPrefix+userName, folderPrefix));

                         o1.write(ContextTag(“Roles”, “Group “userName, “portal_content/”topFolder“/”folderPrefix+userName, folderPrefix));

                         o1.write(ContextTag(“Worksets”, “Group “userName, “portal_content/”topFolder“/”folderPrefix+userName, folderPrefix));

                         o1.write(ContextTag(“Systems”, “Group “userName, “portal_content/”topFolder“/”folderPrefix+userName, folderPrefix));

                         o1.write(ContextTag(“TransportPackages”, “Group “userName, “portal_content/”topFolder“/”folderPrefix+userName, folderPrefix));

                         o1.write(makeRole(prefix“group_”userName“_role”,”Group “userName+” role”,

                              “Group_”userName“_entry_point”,

                              “Group “+userName,

                              “portal_content/”topFolder“/”folderPrefixuserName“/”folderPrefix+”Roles”));

//                         o1.write(CreateFile(userName, topFolder));

                    }

                    o1.write(EndTagsClosingXMLFile());

                    o1.close();

                    File srcFile = new File(origFileName);

                    srcFile = preProcessFile(srcFile);

                    latestMessage = “Finished”;

                    latestStatus = MessageType.INFO;

                    m_request.putValue(“file”, srcFile.toString());

               }

               catch(Exception ex)

               {

                    latestMessage = ex.getLocalizedMessage();

                    latestStatus = MessageType.ERROR;

//                    if(GCLogger.logger().beTraced(TracingConsts.DEBUG))

//                         GCLogger.logger().traceThrowableT(TracingConsts.DEBUG, “Failed to get source file”, ex);

               }

          }

          File preProcessFile(File inFile)

          {

               BufferedReader is;

               File outFile;

               BufferedWriter os;

               try

               {

                    is = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), “UTF8”));

                    outFile = File.createTempFile(“tmp_masscontent”, “.xml”);

                    os = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), “UTF8”));

               }

               catch(FileNotFoundException e)

               {

//                    if(GCLogger.logger().beTraced(TracingConsts.DEBUG))

//                         GCLogger.logger().traceThrowableT(TracingConsts.DEBUG, “File not found”, e);

                    return inFile;

               }

               catch(IOException e)

               {

//                    if(GCLogger.logger().beTraced(TracingConsts.DEBUG))

//                         GCLogger.logger().traceThrowableT(TracingConsts.DEBUG, “Failed while processing the file”, e);

                    return inFile;

               }

               try

               {

                    int len = 80;

                    char buf[] = new char[len];

                    int i;

                    while((i = is.read(buf, 0, len)) != -1)

                         os.write(buf, 0, i);

               }

               catch(IOException e1)

               {

//                    if(GCLogger.logger().beTraced(TracingConsts.DEBUG))

//                         GCLogger.logger().traceThrowableT(TracingConsts.DEBUG, “Failed writting to the file”, e1);

               }

               try

               {

                    os.close();

                    is.close();

               }

               catch(IOException e2)

               {

//                    if(GCLogger.logger().beTraced(TracingConsts.DEBUG))

//                         GCLogger.logger().traceThrowableT(TracingConsts.DEBUG, “Failed closing the file”, e2);

               }

               return outFile;

          }

          public void doOutput(PageProcessor page)

               throws PageException

          {

               String status = (String)m_request.getValue(“status”);

               if(status != null && status.equals(“0”))

                    m_request.putValue(“status”, “1”);

               else

                    super.doOutput(page);

          }

          private static final int PADDING = 5;

          private static final int SPACING = 3;

          private static final String EXECUTE = “doExecute”;

          private static final String STOP = “doStop”;

          private IPortalComponentResponse m_response;

          private IPortalComponentRequest m_request;

          private int state;

          private String result;

          private boolean executeEnabled;

          public CreationDynPage()

          {

               result = “”;

               executeEnabled = true;

          }

     }

     public Creation()

     {

          m_pMode = “cleanAndCreate”;

          m_pIgnore = “false”;

          m_pLogLevel = “real”;

     }

     public DynPage getPage()

     {

          return new CreationDynPage();

     }

     protected void doOnNodeReady(IPortalComponentRequest request, IEvent event)

     {

          super.doOnNodeReady(request, event);

          request.putValue(“status”, “0”);

          DynPage myDynPage = getPage(request, null);

          try

          {

               PageProcessor m_processor = new PageProcessor(request, null, myDynPage);

               m_processor.handleRequest();

          }

          catch(PageException e)

          {

//               if(GCLogger.logger().beTraced(TracingConsts.DEBUG))

//                    GCLogger.logger().traceThrowableT(TracingConsts.DEBUG, “Failed processing a page”, e);

          }

     }

     public static String subst(String oldStr, String newStr, String inString)

     {

          int start = inString.indexOf(oldStr);

          if(start == -1)

          {

               return inString;

          } else

          {

               StringBuffer sb = new StringBuffer();

               sb.append(inString.substring(0, start));

               sb.append(newStr);

               sb.append(inString.substring(start + oldStr.length()));

               return sb.toString();

          }

     }

      private static String GetTimeAndDate()

      {

           GregorianCalendar cal = new GregorianCalendar();

           cal.setTimeZone(TimeZone.getTimeZone(“ECT”));

           cal.setTime(cal.getTime());

           return “”” + String.valueOf(cal.get(1)) + “/” + String.valueOf(cal.get(2)) + “/” + String.valueOf(cal.get(5)) + ” ” + String.valueOf(cal.get(11)) + “:” + String.valueOf(cal.get(12)) + “:” + String.valueOf(cal.get(13)) + “””;

      }

      public static String GenericCreatorTag()

      {

           return “”;

      }

      private String makeRole(String name, String description, String entryPoint, String entryDesc, String folder) {

          String Tag = “<Property name=”parent1″ value=””folder“”/>”;

          Tag = Tag ” <Context name=””name“” objectClass=”com.sapportals.portal.role” create_as=”0″ parent=””folder+””>”;

          Tag = Tag + “”;

          Tag = Tag + “<AttributeValue value=””description“” locale=””/>”;

          Tag = Tag + “<AttributeValue value=””description“” locale=”en”/></Attribute></Attributes>”;

          Tag = Tag + “<Context name=””entryPoint“” objectClass=”com.sapportals.portal.rolefolder” create_as=”0″>”;

          Tag = Tag + “<AttributeValue value=””entryDesc“” locale=””/>”;

          Tag = Tag + “<AttributeValue value=””entryDesc“” locale=”en”/>

This scripting raises an event that is handled by the XML import tool. For this to work in practice, we need to add the iView with the above component toa page that also contains the iView com.sap.portal.generic_creator_component.

The image below shows an example of the page. The top iView is the component that builds the XML, the second iView is the generic creator.

image

To report this post you need to login first.

12 Comments

You must be Logged on to comment or reply to a post.

  1. Daniel Wroblewski
    Hi Michael,

    You are saying that the upload component listens to this event, and when receiving it process the XML file. Is that right?

    How does the component know where the file is?

    Daniel

    (0) 
  2. Debasish Sarkar
    Hello Micheal,

    We are generating a XML file by using some tool from EXCEL. Once the XML is generated it is stored in some location.

    Now as our project need, we need to write a code or use something already providede by SAP to call this script automatically every 12 hours and upload it in portal and excecute it. The whole process needs to be automated without any manual intervention.

    It will be great if you can give your input on this.

    Regards
    Deb
    debasish.sarkar@in.ibm.com

    (0) 
    1. Michael Nicholls Post author
      Hi Deb

      I don’t know of any way to automate the XML upload. I looked at the parameters that worked with the standard XML tool and built the page that I described above. Because this relies on portal eventing, I suspect it can’t be scripted.

      The XML file is ultimately calling standard portal runtime libraries, so you might be able to write your own component that replicates those facilities…

      Good luck

      (0) 
      1. Debasish Sarkar
        Hello Micheal,

        I think I was not clear with my requirement.

        I want to develop a program that will fecth the XML from a predifined place and execute it as we do manually under the XML import tool (Browsing the XML file and then pressing the execute button). Can’t that be automated through a program without manual intervention.

        I don’t know whether I am asking for too much as I don’t have much of development exp.

        Regards
        Deb

        (0) 
        1. Michael Nicholls Post author
          Hi Deb

          Your requirement was clear, but I just don’t know an easy way to do it. The portal is not easy to script for these types of things, which is why you may need to build your own mechanism. Maybe Daniel has a better idea in his blog?

          Cheers

          (0) 
          1. Debasish Sarkar
            Hello Micheal,

            Thats awesome. Will test it and get back to you. Atually we want to automate everything. We totally want to remove manual intervention.

            Your suggestions are really appreciated.

            Regards
            Deb

            (0) 
          2. Debasish Sarkar
            Hello Micheal,

            Can you provide me the jar file corresponding to the following import statement
            com.sapportals.portal.ivs.portalinitialization.IGenericCreatorService;

            I have uploaded the nornal jar files but its not able to resolve the import statement.

            Regards
            Deb
            debasish.sarkar@in.ibm.com

            (0) 
            1. Michael Nicholls Post author
              Hi Deb

              If you use the class locator Eclipse plugin you can find the file com.sap.portal.ivs.init_api.jar.
              You might also need to add com.sap.portal.ivs.api_genericcreator to the ServicesReference in the portalapp.xml file

              Cheers

              (0) 
              1. Debasish Sarkar
                Hello Micheal,

                I failed to get the jar file from anywhere.

                Will it be possible for you to send the project (the code you have written in the wiki) with its jar files/source code to my e-mail address. (Hope I m not asking you to do my part of job :-. Actually automating the XML upload is now the heart of our project and we don’t have any exact solution for it.)

                E-Mail-Id: debasish.sarkar@in.ibm.com

                Also you have written a java script in the above blog that hopefully does the same function. Can we use it as an alternative to upload the XML file.

                Your suggestion/help is always appreciated.

                Regards
                Deb

                (0) 

Leave a Reply