h1. About Activity Plugin {anchor:id=Developer_document.Activity_plug-in}
  
The activity plugin feature was introduced to allow using the activity composer extension and the custom UI component for displaying activity by its type.

h1. How to create activity plugin {anchor:id=Developer_document.Create_activity_plugin}

You should have an idea about the UI Extension Framework. If you have already worked with the UI Extension Framework, it is really easy to create an activity plugin. If not, you have chance to work with it now. You should have a look at [UI Extension Framework|http://wiki.exoplatform.org/xwiki/bin/view/ECM/UI+Extension+Framework].

h2. Create a custom UI component for displaying the activity based on its type {anchor:id=Developer_document.Create_custom_UI_component}

{note}
The Project Code is available [here.|http://wiki.exoplatform.org/xwiki/bin/download/Social/Developer%20Documentation%20Activity%20Plugin/exo.social.samples.activity-plugin.zip]
{note}

When an activity is displayed, UIActivityFactory will look for its registered custom actvity display by activity's type. If not found, UIDefaultActivity will be called for displaying that activity.

For example, in eXo Social, there is an activity of type "exosocial:spaces" created by SpaceActivityPublisher, but now, you want to display it without own UI component instead of the default one. To do that, follow these steps.

*1.* Create a sample project:

{screen}
mvn archetype:generate
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] artifact org.apache.maven.plugins:maven-archetype-plugin: checking for updates from central
[INFO] snapshot org.apache.maven.plugins:maven-archetype-plugin:2.0-alpha-6-SNAPSHOT: checking for updates from central
[INFO] snapshot org.apache.maven.archetype:maven-archetype:2.0-alpha-6-SNAPSHOT: checking for updates from central
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO]    task-segment: [archetype:generate] (aggregator-style)
[INFO] ------------------------------------------------------------------------
[INFO] Preparing archetype:generate
[INFO] No goals needed for project - skipping
[INFO] snapshot org.apache.maven.archetype:archetype-common:2.0-alpha-6-SNAPSHOT: checking for updates from central
[INFO] snapshot org.apache.maven.archetype:archetype-common:2.0-alpha-6-SNAPSHOT: checking for updates from apache.snapshots
[INFO] [archetype:generate {execution: default-cli}]
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
1: remote -> docbkx-quickstart-archetype (null)
2: remote -> gquery-archetype (null)
3: remote -> gquery-plugin-archetype (null)
//....

285: remote -> wicket-scala-archetype (Basic setup for a project that combines Scala and Wicket, 
		depending on the Wicket-Scala project. Includes an example Specs 
		test.)
286: remote -> circumflex-archetype (null)
Choose a number: 76: 76
Choose version: 
1: 1.0
2: 1.0-alpha-1
3: 1.0-alpha-2
4: 1.0-alpha-3
5: 1.0-alpha-4
6: 1.1
Choose a number: : 1
Define value for property 'groupId': : org.exoplatform.social.samples
Define value for property 'artifactId': : exo.social.samples.activity-plugin
Define value for property 'version': 1.0-SNAPSHOT: 1.0.0-SNAPSHOT
Define value for property 'package': org.exoplatform.social.samples: org.exoplatform.social.samples.activityPlugin
Confirm properties configuration:
groupId: org.exoplatform.social.samples
artifactId: exo.social.samples.activity-plugin
version: 1.0.0-SNAPSHOT
package: org.exoplatform.social.samples.activityPlugin
Y: y
{screen}

*2.* Edit the _pom.xml_ file as below.

{code:xml}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.exoplatform.social</groupId>
    <artifactId>social-project</artifactId>
    <version>1.1.0-GA</version>
  </parent>
  <groupId>org.exoplatform.social.samples</groupId>
  <artifactId>exo.social.samples.activity-plugin</artifactId>
  <packaging>jar</packaging>
  <version>1.1.0-GA</version>
  <name>exo.social.samples.activity-plugin</name>
  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <outputDirectory>target/classes</outputDirectory>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.gtmpl</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.exoplatform.portal</groupId>
      <artifactId>exo.portal.webui.core</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.exoplatform.portal</groupId>
      <artifactId>exo.portal.webui.portal</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.exoplatform.social</groupId>
      <artifactId>exo.social.component.core</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.exoplatform.social</groupId>
      <artifactId>exo.social.component.webui</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.exoplatform.social</groupId>
      <artifactId>exo.social.component.service</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</project>
{code}

To use the custom UI component for displaying its activity, you need a class that must be a subclass of _BaseUIActivity_. 

*3.* Call _UISpaceSimpleActivity_

{code:java}
package org.exoplatform.social.samples.activityplugin;

import org.exoplatform.social.webui.activity.BaseUIActivity;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;

@ComponentConfig(
  lifecycle = UIFormLifecycle.class,
  template = "classpath:groovy/social/plugin/space/UISpaceSimpleActivity.gtmpl"
)
public class UISpaceSimpleActivity extends BaseUIActivity {

}
{code}

The _UISpaceSimpleActivity.gtmpl_ template should be created under _main/resources/groovy/social/plugin/space_:

{code:html}
<div>This is a space activity UI component displayed for type "exosocial:spaces"</div>
{code}

An activity builder as [explained later|#Developer_document.What_is_activity_builder] is also needed.

{code:java}
package org.exoplatform.social.samples.activityplugin;

import org.exoplatform.social.core.activity.model.Activity;
import org.exoplatform.social.webui.activity.BaseUIActivity;
import org.exoplatform.social.webui.activity.BaseUIActivityBuilder;

public class SimpleSpaceUIActivityBuilder extends BaseUIActivityBuilder {

  @Override
  protected void extendUIActivity(BaseUIActivity uiActivity, Activity activity) {
    // TODO Auto-generated method stub

  }

}
{code}

*4.* Create the _configuration.xml_ file under _conf/portal_:

{code:xml}
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.exoplaform.org/xml/ns/kernel_1_1.xsd http://www.exoplaform.org/xml/ns/kernel_1_1.xsd" xmlns="http://www.exoplaform.org/xml/ns/kernel_1_1.xsd">
  <external-component-plugins>
    <target-component>org.exoplatform.webui.ext.UIExtensionManager</target-component>
    <component-plugin>
      <name>add.action</name>
      <set-method>registerUIExtensionPlugin</set-method>
      <type>org.exoplatform.webui.ext.UIExtensionPlugin</type>
      <init-params>
        <object-param>
          <name>Simple Space Activity</name>
          <object type="org.exoplatform.social.webui.activity.UIActivityExtension">
            <field name="type">
              <string>org.exoplatform.social.webui.activity.BaseUIActivity</string>
            </field>
            <field name="name">
              <string>exosocial:spaces</string>
            </field>
            <field name="component">
              <string>org.exoplatform.social.samples.activityplugin.UISpaceSimpleActivity</string>
            </field>
            <field name="activityBuiderClass">
              <string>org.exoplatform.social.samples.activityplugin.SimpleSpaceUIActivityBuilder</string>
            </field>
          </object>
        </object-param>
      </init-params>
    </component-plugin>
  </external-component-plugins>
</configuration>
{code}

Note that _{noformat}exosocial:spaces{noformat}_ must have its value matching with the activity's type that you want to display with your UI component.

Assume that you have already built the Social project with version 1.1. If you do not know how to, have a look at [Building from Sources|Main.Building from sources] with [Social 1.1.0-CR01|http://svn.exoplatform.org/projects/social/tags/1.1.0-CR01]. Next, build a sample project and copy the jar file to /tomcat/lib. Then, run Social, create a space and access it, you can see the space's activity of type "exosocial:spaces" is displayed by default in Social:

!images/SimpleSpaceActivity-default.png!

The custom UI component for displaying activity of type "exosocial:spaces" is like below:

!images/SimpleSpaceActivity-custom.png!

*5.* Make the custom UI activity display have the look, feel and function like the default one.

When displaying an activity, you should make sure that the look and feel of the custom UI component is consistent and match with other activities and have the full functions of *Like*, *Comments*. To create another UI component to display, call _UISpaceLookAndFeelActivity_:

{code:java}
package org.exoplatform.social.samples.activityplugin;

import org.exoplatform.social.webui.activity.BaseUIActivity;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;

@ComponentConfig(
  lifecycle = UIFormLifecycle.class,
  template = "classpath:groovy/social/plugin/space/UISpaceLookAndFeelActivity.gtmpl",
  events = {
    @EventConfig(listeners = BaseUIActivity.ToggleDisplayLikesActionListener.class),
    @EventConfig(listeners = BaseUIActivity.ToggleDisplayCommentFormActionListener.class),
    @EventConfig(listeners = BaseUIActivity.LikeActivityActionListener.class),
    @EventConfig(listeners = BaseUIActivity.SetCommentListStatusActionListener.class),
    @EventConfig(listeners = BaseUIActivity.PostCommentActionListener.class),
    @EventConfig(listeners = BaseUIActivity.DeleteActivityActionListener.class, confirm = "UIActivity.msg.Are_You_Sure_To_Delete_This_Activity"),
    @EventConfig(listeners = BaseUIActivity.DeleteCommentActionListener.class, confirm = "UIActivity.msg.Are_You_Sure_To_Delete_This_Comment")
  }
)
public class UISpaceLookAndFeelActivity extends BaseUIActivity {

}
{code}

*6.* Create the _UISpaceLookAndFeelActivity_ template. The easiest way is to copy the content of _UIDefaultActivity.gtmpl_ to this template file:

{code:groovy}
<%
  import org.exoplatform.portal.webui.util.Util;
  import org.exoplatform.webui.form.UIFormTextAreaInput;

  def pcontext = Util.getPortalRequestContext();
  def jsManager = pcontext.getJavascriptManager();
  def labelActivityHasBeenDeleted = _ctx.appRes("UIActivity.label.Activity_Has_Been_Deleted");
  def activity = uicomponent.getActivity();
  def activityDeletable = uicomponent.isActivityDeletable();
%>

<% if (activity) { //process if not null

  jsManager.importJavascript("eXo.social.Util", "/social-resources/javascript");
  jsManager.importJavascript("eXo.social.PortalHttpRequest", "/social-resources/javascript");
  jsManager.importJavascript("eXo.social.webui.UIForm", "/social-resources/javascript");
  jsManager.importJavascript("eXo.social.webui.UIActivity", "/social-resources/javascript");

  def labelComment = _ctx.appRes("UIActivity.label.Comment");
  def labelLike = _ctx.appRes("UIActivity.label.Like");
  def labelUnlike = _ctx.appRes("UIActivity.label.Unlike");
  def labelSource = _ctx.appRes("UIActivity.label.Source");
  def inputWriteAComment = _ctx.appRes("UIActivity.input.Write_A_Comment");
  def labelShowAllComments = _ctx.appRes("UIActivity.label.Show_All_Comments");
  def labelHideAllComments = _ctx.appRes("UIActivity.label.Hide_All_Comments");
  def labelOnePersonLikeThis = _ctx.appRes("UIActivity.label.One_Person_Like_This");
  def labelPeopleLikeThis = _ctx.appRes("UIActivity.label.People_Like_This");
  def labelYouLikeThis = _ctx.appRes("UIActivity.label.You_Like_This");
  def labelYouAndOnePersonLikeThis = _ctx.appRes("UIActivity.label.You_And_One_Person_Like_This");
  def labelYouAndPeopleLikeThis = _ctx.appRes("UIActivity.label.You_And_People_Like_This");

  def likeActivityAction = uicomponent.event("LikeActivity", "true");
  def unlikeActivityAction = uicomponent.event("LikeActivity", "false");

  def commentList = uicomponent.getComments();
  def allComments = uicomponent.getAllComments();
  if (allComments) {
    labelShowAllComments = labelShowAllComments.replace("{0}", allComments.size() + "");
    labelHideAllComments = labelHideAllComments.replace("{0}", allComments.size() + "");

  }
  def displayedIdentityLikes = uicomponent.getDisplayedIdentityLikes();
  def identityLikesNum = 0;
  def labelLikes = null;
  def toggleDisplayLikesAction = uicomponent.event("ToggleDisplayLikes");
  def startTag = "<a onclick=\"$toggleDisplayLikesAction\" id=\"ToggleDisplayListPeopleLikes${activity.id}\" href=\"#ToggleDisplayListPeopleLikes\">";
  def endTag = "</a>";
  if (displayedIdentityLikes != null) {
    identityLikesNum = displayedIdentityLikes.length;
  }
  def commentListStatus = uicomponent.getCommentListStatus();
  def commentFormDisplayed = uicomponent.isCommentFormDisplayed();
  def likesDisplayed = uicomponent.isLikesDisplayed();
  //params for init UIActivity javascript object
  def params = """
    {activityId: '${activity.id}',
     inputWriteAComment: '$inputWriteAComment',
     commentMinCharactersAllowed: ${uicomponent.getCommentMinCharactersAllowed()},
     commentMaxCharactersAllowed: ${uicomponent.getCommentMaxCharactersAllowed()},
     commentFormDisplayed: $commentFormDisplayed,
     commentFormFocused: ${uicomponent.isCommentFormFocused()}
    }
  """
  jsManager.addOnLoadJavascript("initUIActivity${activity.id}");
  //make sures commentFormFocused is set to false to prevent any refresh to focus, only focus after post a comment
  uicomponent.setCommentFormFocused(false);
  def activityUserName, activityUserProfileUri, activityImageSource, activityContentBody, activityPostedTime;
  def commentFormBlockClass = "", listPeopleLikeBlockClass = "", listPeopleBGClass = "";
  if (!commentFormDisplayed) {
    commentFormBlockClass = "DisplayNone";
  }

  if (!likesDisplayed) {
    listPeopleLikeBlockClass = "DisplayNone";
  }

  if (uicomponent.isLiked()) {
    if (identityLikesNum > 1) {
      labelLikes = labelYouAndPeopleLikeThis.replace("{start}", startTag).replace("{end}", endTag).replace("{0}", identityLikesNum + "");
    } else if (identityLikesNum == 1) {
      labelLikes = labelYouAndOnePersonLikeThis.replace("{start}", startTag).replace("{end}", endTag);
    } else {
      labelLikes = labelYouLikeThis;
    }
  } else {
    if (identityLikesNum > 1) {
        labelLikes = labelPeopleLikeThis.replace("{start}", startTag).replace("{end}", endTag).replace("{0}", identityLikesNum + "");
    } else if (identityLikesNum == 1) {
        labelLikes = labelOnePersonLikeThis.replace("{start}", startTag).replace("{end}", endTag);
    }
  }

  if (!labelLikes) {
   //hides diplayPeopleBG
   listPeopleBGClass = "DisplayNone";
  }

  activityContentTitle = activity.title;
  activityPostedTime = uicomponent.getPostedTimeString(activity.postedTime);
  activityUserName = uicomponent.getUserFullName(activity.userId);
  activityUserProfileUri = uicomponent.getUserProfileUri(activity.userId);

  activityImageSource = uicomponent.getUserAvatarImageSource(activity.userId);
  if (!activityImageSource)  {
    activityImageSource = "/social-resources/skin/ShareImages/SpaceImages/SpaceLogoDefault_61x61.gif";
  }

%>

<div class="UIActivity">
  <script type="text/javascript">
    function initUIActivity${activity.id}() {
      new eXo.social.webui.UIActivity($params);
    }
  </script>

  <% uiform.begin() %>
  <div class="NormalBox clearfix">
    <a class="Avatar" title="$activityUserName" href="$activityUserProfileUri">
      <img title="$activityUserName" src="$activityImageSource" alt="$activityUserName" height="54px" width="56px">
    </a>
    <div class="ContentBox" id="ContextBox${activity.id}">
      <div class="TitleContent clearfix">
        <div class="Text">
          <a title="$activityUserName" href="$activityUserProfileUri">$activityUserName</a>
        </div>
      <% if (activityDeletable) {%>
        <div onclick="<%= uicomponent.event("DeleteActivity", uicomponent.getId(), ""); %>" class="CloseContentBoxNormal" id="DeleteActivityButton${activity.id}"><span></span></div>
      <%}%>
      </div>
      <div class="Content">
        $activityContentTitle (from custom UI component)<br>
      </div>
      <div class="LinkCM">
        <span class="DateTime">$activityPostedTime *</span>
      <% def toggleDisplayCommentAction = uicomponent.event('ToggleDisplayCommentForm', null, false);
         def commentLink = "";
      %>
        <a class="LinkCM $commentLink" onclick="$toggleDisplayCommentAction" id="CommentLink${activity.id}" href="#comment">
          $labelComment
        </a> |
      <% if (uicomponent.isLiked()) { %>
        <a onclick="$unlikeActivityAction" class="LinkCM" id="UnLikeLink${activity.id}" href="#unlike">
          $labelUnlike
        </a>
      <% } else { %>
        <a onclick="$likeActivityAction" class="LinkCM" id="LikeLink${activity.id}" href="#like">
          $labelLike
        </a>
      <% }%>
      </div>
    </div>

    <div class="ListPeopleLikeBG $listPeopleBGClass">
      <div class="ListPeopleLike">
        <div class="ListPeopleContent">
        <% if (!labelLikes) labelLikes = ""; %>
          <div class="Title">$labelLikes</div>
          <div class="$listPeopleLikeBlockClass">
          <%
          //def personLikeFullName, personLikeProfileUri, personLikeAvatarImageSource;

          displayedIdentityLikes.each({
            personLikeFullName = uicomponent.getUserFullName(it);
            personLikeProfileUri = uicomponent.getUserProfileUri(it);
            personLikeAvatarImageSource = uicomponent.getUserAvatarImageSource(it);
            if (!personLikeAvatarImageSource) {
              personLikeAvatarImageSource = "/social-resources/skin/ShareImages/activity/AvatarPeople.gif";
            }
            %>
              <a class="AvatarPeopleBG" title="$personLikeFullName" href="$personLikeProfileUri">
                <img width="47px" height="47px" src="$personLikeAvatarImageSource" alt="$personLikeFullName" title="$personLikeFullName" />
              </a>
           <% })%>
          </div>
          <div class="ClearLeft">
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <div class="CommentListInfo">
    <% if (uicomponent.commentListToggleable()) {
    def showAllCommentsAction = uicomponent.event("SetCommentListStatus", "all");
    def hideAllCommentsAction = uicomponent.event("SetCommentListStatus", "none");
    %>
      <div class="CommentBlock">
        <div class="CommentContent">
          <div class="CommentBorder">
          <% if (commentListStatus.getStatus().equals("latest") || commentListStatus.getStatus().equals("none")) { %>
            <a onclick="$showAllCommentsAction" href="#show-all-comments">
              $labelShowAllComments
            </a>
          <% } else if (commentListStatus.getStatus().equals("all")) { %>
            <a onclick="$hideAllCommentsAction" href="#hide-all-comments">
              $labelHideAllComments
            </a>
          <% } %>
          </div>
        </div>
      </div>
    <% } %>
    </div>
  <% if (allComments.size() > 0) { %>
    <div class="DownIconCM"><span></span></div>
  <% }%>

  <%
  def commenterFullName, commenterProfileUri, commenterImageSource, commentMessage, commentPostedTime;
  def first = true, commentContentClass;
  commentList.each({
    if (first & !uicomponent.commentListToggleable()) {
      commentContentClass = "CommentContent";
      first = false;
    } else {
      commentContentClass = "";
    }
    commenterFullName = uicomponent.getUserFullName(it.userId);
    commenterProfileUri = uicomponent.getUserProfileUri(it.userId);
    commenterImageSource = uicomponent.getUserAvatarImageSource(it.userId);
    if (!commenterImageSource) {
      commenterImageSource = "/social-resources/skin/ShareImages/activity/AvatarPeople.gif";
    }
    commentMessage = it.title;
    commentPostedTime = uicomponent.getPostedTimeString(it.postedTime);
  %>
    <div id="CommentBlock${activity.id}" class="CommentBox clearfix">
      <a class="AvatarCM" title="$commenterFullName" href="$commenterProfileUri">
        <img src="$commenterImageSource" alt="$commenterFullName" height="36px" width="38px">
      </a>
      <div class="ContentBox">
        <div class="Content">
          <a href="$commenterProfileUri"><span class="Commenter">$commenterFullName<span></a><br />
            $commentMessage
          <br/>
        </div>
        <div class="LinkCM">
          <span class="DateTime">$commentPostedTime</span>
        </div>
      </div>
    <%
      if (uicomponent.isCommentDeletable(it.userId)) {
    %>
      <div onclick="<%= uicomponent.event("DeleteComment", uicomponent.id, it.id); %>" class="CloseCMContentHilight"><span></span></div>
    <% } %>
    </div>
  <% }) %>

    <div class="CommentBox $commentFormBlockClass clearfix" id="CommentFormBlock${activity.id}">
      <% uicomponent.renderChild(UIFormTextAreaInput.class); %>
      <input type="button" onclick="<%= uicomponent.event("PostComment") %>" value="$labelComment" class="CommentButton DisplayNone" id="CommentButton${activity.id}" />
    </div>

  </div>
  <% uiform.end() %>
</div>
<% } else { %> <!-- activity deleted -->
<div class="UIActivity Deleted">$labelActivityHasBeenDeleted</div>
<% }%>
{code}

And you should make needed modifications for this template:

{code:groovy}
<div class="Content">
  $activityContentTitle (from custom UI component)<br>
</div>
{code}

*7.* Reconfigure the _configuration.xml_ file:

{code:xml}
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.exoplaform.org/xml/ns/kernel_1_1.xsd http://www.exoplaform.org/xml/ns/kernel_1_1.xsd" xmlns="http://www.exoplaform.org/xml/ns/kernel_1_1.xsd">
  <external-component-plugins>
    <target-component>org.exoplatform.webui.ext.UIExtensionManager</target-component>
    <component-plugin>
      <name>add.action</name>
      <set-method>registerUIExtensionPlugin</set-method>
      <type>org.exoplatform.webui.ext.UIExtensionPlugin</type>
      <init-params>
        <object-param>
          <name>Look And Feel Space Activity</name>
          <object type="org.exoplatform.social.webui.activity.UIActivityExtension">
            <field name="type">
              <string>org.exoplatform.social.webui.activity.BaseUIActivity</string>
            </field>
            <field name="name">
              <string>exosocial:spaces</string>
            </field>
            <field name="component">
              <string>org.exoplatform.social.samples.activityplugin.UISpaceLookAndFeelActivity</string>
            </field>
            <field name="activityBuiderClass">
              <string>org.exoplatform.social.samples.activityplugin.SimpleSpaceUIActivityBuilder</string>
            </field>
          </object>
        </object-param>
      </init-params>
    </component-plugin>
  </external-component-plugins>
</configuration>
{code}

*8.* Rebuild the sample project, copy the *.jar* file to tomcat/lib. Run the server again and see the result:

!images/LookAndFeelSpaceActivity.png!

{note}
Currently, you have to copy and paste in the template file. By this way, you have full control of the UI but it is not a good way when there are changes in UIDefaultActivity. This will be improved soon so that no copy/paste is needed.
{note}

h3. What is ActivityBuilder? {anchor:id=Developer_document.What_is_activity_builder}
ActivityBuilder is one class which is used to get values of _ExoSocialActivity_ to set to UIActivity for displaying. eXo Social provides the BaseUIActivityBuilder class for developers to extend and customize their own activity builder easily and properly.

For example, to write your own UILinkActivityBuilder, you just need to extend BaseUIActivityBuilder and then customize attributes and behaviors of the activity builder as below.

{code:java}
public class UILinkActivityBuilder extends BaseUIActivityBuilder {
  private static final Log LOG = ExoLogger.getLogger(UILinkActivityBuilder.class);
  @Override
  protected void extendUIActivity(BaseUIActivity uiActivity, ExoSocialActivity activity) {
    UILinkActivity uiLinkActivity = (UILinkActivity) uiActivity;
    Map<String, String> templateParams = activity.getTemplateParams();   
    uiLinkActivity.setLinkSource(templateParams.get(UILinkActivityComposer.LINK_PARAM));
    uiLinkActivity.setLinkTitle(templateParams.get(UILinkActivityComposer.TITLE_PARAM));
    uiLinkActivity.setLinkImage(templateParams.get(UILinkActivityComposer.IMAGE_PARAM));
    uiLinkActivity.setLinkDescription(templateParams.get(UILinkActivityComposer.DESCRIPTION_PARAM));
    uiLinkActivity.setLinkComment(templateParams.get(UILinkActivityComposer.COMMENT_PARAM));
  }
}
{code}

{note}
To learn more about ActivityBuilder, refer to the [BaseUIActivity class.|http://svn.exoplatform.org/projects/social/trunk/component/webui/src/main/java/org/exoplatform/social/webui/activity/BaseUIActivity.java]
{note}

h2. Create a composer extension for composing activity on the UI composer and display it on the activity stream {anchor:id=Developer_document.Create_composer_extension}
The UIActivityComposer is an extended class of UIContainer that is used to display inputs for users to create their own activities. To write your own activity composer, it is recommended that you use the UIActivityComposer available in eXo Social.

For example, to create an input component for inserting video links into your activity, do the following steps:

*1.* Write UIVideoActivityComposer which extends UIActivityComposer. The UIActivityComposer allows you to input extended activities (for example, adding videos, links or documents) on the UI composer.

{code:java}
package org.exoplatform.social.plugin.videolink;

import org.exoplatform.social.plugin.videolink.util.VideoEmbedTool;
@ComponentConfig(
        template = "classpath:groovy/social/plugin/videolink/UIVideoActivityComposer.gtmpl",
        events = {
                @EventConfig(listeners = UIVideoActivityComposer.SearchVideo.class),
                @EventConfig(listeners = UIVideoActivityComposer.SelectVideoFromResultList.class),
                @EventConfig(listeners = UIVideoActivityComposer.AttachActionListener.class),
                @EventConfig(listeners = UIVideoActivityComposer.ChangeLinkContentActionListener.class),
                @EventConfig(listeners = UIActivityComposer.CloseActionListener.class),
                @EventConfig(listeners = UIActivityComposer.SubmitContentActionListener.class),
                @EventConfig(listeners = UIActivityComposer.ActivateActionListener.class)
        }
)

public class UIVideoActivityComposer extends UIActivityComposer {

  public static final String LINK_PARAM = "link";
  public static final String IMAGE_PARAM = "image";
  public static final String TITLE_PARAM = "title";
  public static final String HTML_PARAM = "htmlembed";
  public static final String COMMENT_PARAM = "comment";

  private static final String HTTP = "http://";
  private static final String HTTPS = "https://";
  private JSONObject videoJson;
  private boolean linkInfoDisplayed_ = false;
  private Map<String, String> templateParams;

  /**
   * The constructor.
   */
  public UIVideoActivityComposer() {
    setReadyForPostingActivity(false);
    addChild(new UIFormStringInput("InputLink", "InputLink", null));
  }
  /**
   * Set the link info to be displayed.
   *
   * @param displayed
   */
  public void setLinkInfoDisplayed(boolean displayed) {
    linkInfoDisplayed_ = displayed;
  }
  
  /**
   * Set the template params.
   *
   * @param templateParams
   */
  public void setTemplateParams(Map<String, String> templateParams) {
    this.templateParams = templateParams;
  }

  /**
   * Get the template params.
   */
  public Map<String, String> getTemplateParams() {
    return templateParams;
  }
  
  /**
   * Clear the video json.
   */
  public void clearVideoJson() {
    videoJson = null;
  }

  /**
   * Get the video json.
   */
  public JSONObject getVideoJson() {
    return videoJson;
  }

  /**
   * Set the link.
   
   * @param url
   * @throws Exception
   */
  private void setLink(String url) throws Exception {
    if (!(url.contains(HTTP) || url.contains(HTTPS))) {
      url = HTTP + url;
    }

    videoJson = VideoEmbedTool.getoembedData(url);
    templateParams = new HashMap<String, String>();
    templateParams.put(LINK_PARAM, url);
    templateParams.put(TITLE_PARAM, videoJson.getString(VideoEmbedTool.OEMBED_TITLE));
    templateParams.put(HTML_PARAM, videoJson.getString(VideoEmbedTool.OEMBED_HTML));
    setLinkInfoDisplayed(true);
  }

  static public class AttachActionListener extends EventListener<UIVideoActivityComposer> {

    @Override
    public void execute(Event<UIVideoActivityComposer> event) throws Exception {
      WebuiRequestContext requestContext = event.getRequestContext();
      UIVideoActivityComposer uiComposerLinkExtension = event.getSource();
      String url = requestContext.getRequestParameter(OBJECTID);
      try {
        uiComposerLinkExtension.setLink(url.trim());
      } catch (Exception e) {
        uiComposerLinkExtension.setReadyForPostingActivity(false);
        return;
      }
      requestContext.addUIComponentToUpdateByAjax(uiComposerLinkExtension);
      event.getSource().setReadyForPostingActivity(true);
    }
  }

  static public class ChangeLinkContentActionListener extends EventListener<UIVideoActivityComposer> {
    @Override
    public void execute(Event<UIVideoActivityComposer> event) throws Exception {
      WebuiRequestContext requestContext = event.getRequestContext();
      UIVideoActivityComposer uiComposerLinkExtension = event.getSource();
      
      Map<String, String> tempParams = new HashMap<String, String>();
      
      uiComposerLinkExtension.setTemplateParams(tempParams);
      requestContext.addUIComponentToUpdateByAjax(uiComposerLinkExtension);
      UIComponent uiParent = uiComposerLinkExtension.getParent();
      if (uiParent != null) {
        uiParent.broadcast(event, event.getExecutionPhase());
      }
    }
  }

  public static class SelectVideoFromResultList extends EventListener<UIVideoActivityComposer>{
    @Override
    public void execute(Event<UIVideoActivityComposer> event) throws Exception {
      WebuiRequestContext requestContext = event.getRequestContext();
      UIVideoActivityComposer uiComposerLinkExtension = event.getSource();

    }
  }

  public static class SearchVideo extends EventListener<UIVideoActivityComposer>{

    @Override
    public void execute(Event<UIVideoActivityComposer> event) throws Exception {
      WebuiRequestContext requestContext = event.getRequestContext();
      UIVideoActivityComposer uiComposerLinkExtension = event.getSource();


    }
  }

  @Override
  public void onPostActivity(PostContext postContext, UIComponent source,
                             WebuiRequestContext requestContext, String postedMessage) throws Exception {
                             
    templateParams.put(COMMENT_PARAM, postedMessage);
    setTemplateParams(templateParams);
    if (templateParams.size() == 0) {
      uiApplication.addMessage(new ApplicationMessage("UIComposer.msg.error.Empty_Message",
              null,
              ApplicationMessage.WARNING));
      return;
    }
    String title = "Shared a video: <a href=\"${" + LINK_PARAM + "}\">${" + TITLE_PARAM + "} </a>";
    ExoSocialActivity activity = new ExoSocialActivityImpl(userIdentity.getId(),
            UIVideoActivity.ACTIVITY_TYPE,
            title,
            null);
    activity.setTemplateParams(templateParams);

    if (postContext == UIComposer.PostContext.SPACE) {
    
      UIActivitiesContainer activitiesContainer = uiDisplaySpaceActivities.getActivitiesLoader().getActivitiesContainer();
      activitiesContainer.addActivity(activity);
      requestContext.addUIComponentToUpdateByAjax(activitiesContainer);
      requestContext.addUIComponentToUpdateByAjax(uiComposer);
    } else if (postContext == PostContext.USER) {
      UIUserActivitiesDisplay uiUserActivitiesDisplay = (UIUserActivitiesDisplay) getActivityDisplay();
      String ownerName = uiUserActivitiesDisplay.getOwnerName();
      Identity ownerIdentity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME,
              ownerName, false);

      activityManager.saveActivity(ownerIdentity, activity);

      if (uiUserActivitiesDisplay.getSelectedDisplayMode() == UIUserActivitiesDisplay.DisplayMode.MY_STATUS) {
        UIActivitiesContainer activitiesContainer = uiUserActivitiesDisplay.getActivitiesLoader().getActivitiesContainer();
        if (activitiesContainer.getChildren().size() == 1) {
          uiUserActivitiesDisplay.setSelectedDisplayMode(UIUserActivitiesDisplay.DisplayMode.MY_STATUS);
        } else {
          activitiesContainer.addActivity(activity);
          requestContext.addUIComponentToUpdateByAjax(activitiesContainer);
          requestContext.addUIComponentToUpdateByAjax(uiComposer);
        }
      } else{
        uiUserActivitiesDisplay.setSelectedDisplayMode(UIUserActivitiesDisplay.DisplayMode.MY_STATUS);
      }
    }
  }
}
{code}

*2.* Use the BaseUIActivity class to write and customize the UIActivity display as below:

{code:java}
package org.exoplatform.social.plugin.videolink;
import org.exoplatform.social.webui.activity.BaseUIActivity;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.config.annotation.EventConfig;
@ComponentConfig(lifecycle = UIFormLifecycle.class, template = "classpath:groovy/social/plugin/videolink/UIVideoActivity.gtmpl", events = {
  @EventConfig(listeners = BaseUIActivity.ToggleDisplayLikesActionListener.class),
  @EventConfig(listeners = BaseUIActivity.ToggleDisplayCommentFormActionListener.class),
  @EventConfig(listeners = BaseUIActivity.LikeActivityActionListener.class),
  @EventConfig(listeners = BaseUIActivity.SetCommentListStatusActionListener.class),
  @EventConfig(listeners = BaseUIActivity.PostCommentActionListener.class),
  @EventConfig(listeners = BaseUIActivity.DeleteActivityActionListener.class, confirm = "UIActivity.msg.Are_You_Sure_To_Delete_This_Activity"),
  @EventConfig(listeners = BaseUIActivity.DeleteCommentActionListener.class, confirm = "UIActivity.msg.Are_You_Sure_To_Delete_This_Comment")
 }
)
public class UIVideoActivity extends BaseUIActivity {
  public static final String ACTIVITY_TYPE = "VIDEO_ACTIVITY";
  private String linkSource = "";
  private String linkTitle = "";
  private String linkHTML = "";
  private String linkComment = "";
  
  /**
   * Get the link comment.
   */
  public String getLinkComment() {
    return linkComment;
  }
  
  /**
   * Set the link comment.
   *
   * @param linkComment
   */
  public void setLinkComment(String linkComment) {
    this.linkComment = linkComment;
  }
  
  /**
   * Get the link html.
   */
  public String getLinkHTML() {
    return linkHTML;
  }
  
  /**
   * Set the link html.
   *
   * @param linkHTML
   */
  public void setLinkHTML(String linkHTML) {
    this.linkHTML = linkHTML;
  }
  
  /**
   * Get the link source.
   */
  public String getLinkSource() {
    return linkSource;
  }
  
  /**
   * Set the link source.
   *
   * @param linkSource
   */
  public void setLinkSource(String linkSource) {
    this.linkSource = linkSource;
  }
  
  /**
   * Get the link title.
   */
  public String getLinkTitle() {
    return linkTitle;
  }
  
  /**
   * Set the link title.
   *
   * @param linkTitle
   */
  public void setLinkTitle(String linkTitle) {
    this.linkTitle = linkTitle;
  }
}
{code}

*3.* Use the _UIVideoActivityBuilder_ class to get values of _ExoSocialActivity_ that are set to UIVideoActivity for displaying.

{code:java}
package org.exoplatform.social.plugin.videolink;
import java.util.Map;
import org.exoplatform.social.core.activity.model.ExoSocialActivity;

public class UIVideoActivityBuilder extends BaseUIActivityBuilder {
  private static final Log LOG = ExoLogger.getLogger(UIVideoActivityBuilder.class);
  @Override
  protected void extendUIActivity(BaseUIActivity uiActivity, ExoSocialActivity activity) {
  UIVideoActivity uiVideoActivity = (UIVideoActivity) uiActivity;
  Map<String, String> templateParams = activity.getTemplateParams();
    uiVideoActivity.setLinkSource(templateParams.get(UIVideoActivityComposer.LINK_PARAM));
    uiVideoActivity.setLinkTitle(templateParams.get(UIVideoActivityComposer.TITLE_PARAM));
    uiVideoActivity.setLinkImage(templateParams.get(UIVideoActivityComposer.IMAGE_PARAM));
    uiVideoActivity.setLinkHTML(templateParams.get(UIVideoActivityComposer.HTML_PARAM));
    uiVideoActivity.setLinkComment(templateParams.get(UIVideoActivityComposer.COMMENT_PARAM));
  }
}
{code}

{note}
You can check out the [source code|https://github.com/exosocial/exo.social.extras.youtube-composer-plugin] to get more details.
{note}