Saturday, 7 June 2014

Creating virtual portal in websphere portal 8

Virtual portal :- Its a copy of portal with limited capabilities. People create multiple virtual portals to host different set of applications like account,finance,health care each of them having different url and different navigation structure.

Example{Below urls will be redirected to corresponding virtual portal depending on config} :-
http://localhost:10039/wps/portal/finance
http://localhost:10039/wps/portal/accounts
http://localhost:10039/wps/portal/healthcare


Step 1 :- Now login to websphere portal admin console and click on manage virtual portals under Virtual-Portals as given below




Step 2 :- Now click on create new virtual portal button on right hand side and fill below details


Virtual post hostname :- You can give a domain name and map to same ip address as base portal
Context  :- This is the value you case use it after wps/portal if it is hospitality then wps/portal/hospitality

Step 3 :- Now click ok virtual portal will be created. It will take some time.



Step 4 :- Now you can access your virtual portal two ways
                A) http://localhost:10039/wps/portal/accounts {By default this redirects to B}
                B) http://accountstest:10039/wps/portal



Monday, 2 June 2014

Command Cache implementation in portal

Command Cache :- This is used as a place holder for data and replace it at a particular interval as desired .

 Step 1:- First you need to check whether your web-sphere portal is capable of caching the data



Step 2 :- Now click on Dynamic cache service under container services and check whether below check box is selected



Step 3 :- 
  1. Create a Java class that extends CacheableCommandImpl class, this class provides logic to cache data by providing life cycle for your class. The CacheableCommandImpl is abstract class so in order to make a concrete class you will have to override  its isReadyToCallExecute() and performExecute() method

  2. The CacheableCommandImpl class provides life cycle for the cache-able object, it will call the isReadyToCallExecute()method of your class to check if your class is ready to execute. You can use this method to check if your data access part is ready. If it is not ready you can write custom code to return false

  3. The performExecute() method of your class is the place were you will be having your custom code to get data . In my example class name is CachableContent
//Class code
package com.ibm.cachableClass;

import java.util.Random;

import com.ibm.websphere.command.CacheableCommandImpl;

public class CachableContent extends CacheableCommandImpl {
private static final long serialVersionUID = 6243454554964886940L;
private int randomValue = 1;
private int ComputedValue = 0;

public CachableContent(int value) {
this.randomValue = value;
// TODO Auto-generated constructor stub
}

@Override
public boolean isReadyToCallExecute() {
// TODO Auto-generated method stub
return true;
}

@Override
public void performExecute() throws Exception {
System.out.println("enterring into perform execute");
//We will get updated computed value for every 60 seconds
setComputedValue(randomValue+randomValue);
// TODO Auto-generated method stub

}

public int getRandomValue() {
return randomValue;
}

public void setRandomValue(int randomValue) {
this.randomValue = randomValue;
}

public int getComputedValue() {
return ComputedValue;
}

public void setComputedValue(int computedValue) {
ComputedValue = computedValue;
}

}

Step 4 :-  Now create a portlet to access the CachableContent


package com.ibm.cachableportlet;

import java.io.*;
import javax.portlet.*;

import com.ibm.cachableClass.CachableContent;

/**
 * A sample portlet
 */
public class CachablePortlet extends javax.portlet.GenericPortlet {
/**
* @see javax.portlet.Portlet#init()
*/
public void init() throws PortletException{
super.init();
}

/**
* Serve up the <code>view</code> mode.
* 
* @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());

CachableContent cc = new CachableContent();
                //will actually call the perform execute method
                cc.execute();
int randValue = cc.getRandomValue();
//Depending on the time you set this will be refreshed
response.getWriter().println("CachablePortlet#doView()"+randValue);
}

/**
* Serve up the <code>edit</code> mode.
* 
* @see javax.portlet.GenericPortlet#doEdit(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// TODO: auto-generated method stub
}

/**
* Serve up the <code>help</code> mode.
* 
* @see javax.portlet.GenericPortlet#doHelp(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
protected void doHelp(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// TODO: auto-generated method stub
}

/**
* Process an action request.
* 
* @see javax.portlet.Portlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
*/
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
// TODO: auto-generated method stub
}

}


Step 5 :-  Now create the cachespec.xml to specify the time and place it under web-inf like below



<?xml version="1.0" ?>
<!DOCTYPE cache SYSTEM "cachespec.dtd">
<cache>
  <cache-entry>
    <class> command</class>
       <sharing-policy>not-shared</sharing-policy>
       <name> com.ibm.cachableClass.CachableContent.class</name>
       <cache-id>
          <component type="method" id="getRandomValue">
             <required>true</required >
          </component>
          <priority>1</priority>
             <timeout>60</timeout >
          </cache-id>
   </cache-entry>
</cache>

               Mention the method you are calling and the time interval in which it should refresh. Now the random number will be regenerated for every 60 seconds.


Step 6 :- Deploy this in the portal server and observe the change of number for every 60 second. If you do a refresh of the page

Sunday, 1 June 2014

Dynaacache in websphere portal


Steps to implement dynacache :- 
                              Dynacache is a place to store data . We can store objects and use them when ever required for future use. WebSphere will be responsible for maintaining and managing these objects. We can change the configurations from was admin console.

Step 1 :-   Create or check existing cache instance in websphere portal . If it doesn't exist create one. Navigate to below location in was console




Step 2 :-  Now click on object cache instances and create a new one


Step 3 :- Click save and then check for newly created cache instance then restart the portal server




Step 4 :- Now create a portlet and write code to lookup for service object to access dynacache object

package com.ibm.dynacacheportlet;

import java.io.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.portlet.*;

import com.ibm.websphere.cache.DistributedMap;

/**
 * A sample portlet
 */
public class DynacachePortlet extends javax.portlet.GenericPortlet {
/**
* @see javax.portlet.Portlet#init()
*/
//Distributed map which consists of all stored objects
private DistributedMap appCache = null;
public void init() throws PortletException{
super.init();
InitialContext ctx;

        try {
            ctx = new InitialContext();
            appCache = (DistributedMap) ctx.lookup("tutorialCache");
        } catch (NamingException e) {
            // TODO need to change the exception handling...
            e.printStackTrace();
        }
}

/**
* Serve up the <code>view</code> mode.
*
* @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// Set the MIME type for the render response
System.out.println("enterring");
response.setContentType(request.getResponseContentType());
appCache.put("Name", "renault");
String mapValue = (String) appCache.get("Name");
System.out.println("String value :- "+ mapValue);
response.getWriter().println("DynacachePortlet#doView()"+ mapValue);
}

/**
* Serve up the <code>edit</code> mode.
*
* @see javax.portlet.GenericPortlet#doEdit(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// TODO: auto-generated method stub
}

/**
* Serve up the <code>help</code> mode.
*
* @see javax.portlet.GenericPortlet#doHelp(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
protected void doHelp(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// TODO: auto-generated method stub
}

/**
* Process an action request.
*
* @see javax.portlet.Portlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
*/
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
// TODO: auto-generated method stub
}

}






Thursday, 29 May 2014

Configuring WebSphere Portal for site analysis logging

Configuring WebSphere Portal for site analysis logging

 They need statistic on the number of logon's and pages access. By default WebSphere site analysis logging is not enable. Portal provides server side analytic's for client side analytic's we need to depend on core-metrics.

1) Open WebSphere admin console
2) In the navigation open the Resources section
3) Click Resource Environment Providers.
4) In the Resource Environment Providers
* If running standalone, select Browse nodes and select the node.
* If installed in a cluster, select Browse Clusters and select the cluster.
5) Select the service to which you want to make changes. In this case select "WP SiteAnalyzerLogService"
6) Click Custom Properties.

7) Restart the server to make the changes become effective.

Now you can see logs in sa.log under wp_profile

Saturday, 24 May 2014

Integrating portal with facebook

Step 1 :-
Create two apps one for portal and other for myportal  in facebook
Step2 :-
ConfigEngine.bat enable-identityprovider-tai -DWasUserId=wpsadmin -DWasPassword=passw0rd_123 -Didp.providerlist=facebook -Dfacebook_apps=app,pub -Dfacebook_app_id=3086542391078 -Dfacebook_app_secret=ea777462ce3619e2962dcfec97fbe8 -Dfacebook_app_site=http://wportal8.atech.com:10039/wps/myportal -Dfacebook_pub_id=14915261877474 -Dfacebook_pub_secret=0c493581530f3cc47d45ff870654eb -Dfacebook_pub_site=http://wportal8.atech.com:10039/wps/portal
Stpe 3 :- Go to login portlet and add below preferences
show_idp_option =true
show_idp_max =1
show_idp_freeform_field =false
Stpe 4:- Go to profile management and add below preferences
show_idp_option =true
show_idp_max=1
show_idp_freeform_field=false
facebook.required= ibm-primaryEmail|email; givenName|first_name; sn|last_name;uid|id;preferredLanguage|locale
facebook.optional= ibm-primaryEmail|email;givenName|first_name;
sn|last_name;uid|id;preferredLanguage|locale
facebook.protocol= openid.ax

Step 5:- Restart the server


Infocenter Link:
http://www-10.lotus.com/ldd/portalwiki.nsf/xpDocViewer.xsp?lookupName=IBM+WebSphere+Portal+8+Product+Documentation#action=openDocument&res_title=Integrating_with_OpenID_authentication_wp8&content=pdcontent




Monday, 19 May 2014

Credential vault implementation in websphere portal

Credential vault :- Is the place where a particular user can store his credentials and retrieve it when ever required securely. For example when you are accessing your employee portal you want to store your other portal credentials and when ever you click on a link. Which redirects to that portal and you want to login automatically.

Types of credential vault :-
A) User managed vault
B) Admin managed vault

Types of credentials :-
A) Active credential
B) Passive credential

Active credentials :- User wont be able to retrieve credentials but he will be able to pass it to back end service by form or basic authentication
Passive credentials :- User will be able to access his password and use it for other purposes

Technical overview :-
    CredentialVaultService
    Vault adapter
    CredentialSlotConfig

Sample portlet applications
This article provides code examples for four sample portlet applications. You can install the applications to understand different ways to create vault slots, and to set and get credentials into vault slots.

The credential vault provided by WebSphere Portal defines four types of vault slots:
Portlet private slot: Stores user credentials that are not shared among portlets. The Private Slot Portlet application demonstrates the private slot.

Shared slot: Stores user credentials that are shared among the user's portlets. The Shared Slot Portlet application demonstrates the shared slot.

Administrative slot: Allows each user to store a secret for an administrator-defined resource (for example, Lotus Notes). The Administrative Slot Portlet application demonstrates the administrative slot.

System slot: Stores system credentials where the actual secret is shared among all users and portlets. The System Slot Portlet application demonstrates system slot.

Portlets belonging to all of these sample applications, except for System Slot Portlet Application, support both edit and view modes. A user can select edit mode to store credentials into the vault and view mode to see credentials that have been set.

Example :- 
Portlet code :-
package com.ibm.credentialvault;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import com.ibm.portal.ObjectID;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.credentialvault.CredentialSlotConfig;
import com.ibm.portal.portlet.service.credentialvault.CredentialTypes;
import com.ibm.portal.portlet.service.credentialvault.CredentialVaultException;
import com.ibm.portal.portlet.service.credentialvault.CredentialVaultService;
import com.ibm.portal.portlet.service.credentialvault.credentials.HttpFormBasedAuthCredential;
import com.ibm.portal.portlet.service.credentialvault.credentials.UserPasswordPassiveCredential;


/**
 * A sample portlet
 */
public class CredentialVaultPortlet extends javax.portlet.GenericPortlet {
private CredentialVaultService cvs;
private static String sharedSlotResourceName ="loginslot";

/**
* @see javax.portlet.Portlet#init()
*/
public void init() throws PortletException{
super.init();
try{
javax.naming.Context ctx = new  javax.naming.InitialContext();
PortletServiceHome cvsHome = (PortletServiceHome)ctx.lookup("portletservice/com.ibm.portal.portlet.service.credentialvault.CredentialVaultService" );
cvs  = (CredentialVaultService)cvsHome.getPortletService (CredentialVaultService. class );
}catch(Exception e){

}
     
}

/**
* Serve up the <code>view</code> mode.
*
* @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());

//
// Passive credentials
//
   String slot = getSharedSlotId(request);
        if (slot != null)
        {      
          try{
          UserPasswordPassiveCredential credential =(UserPasswordPassiveCredential) cvs.getCredential
                                  (slot, "UserPasswordPassive", new HashMap<String,String>(), request);
          System.out.println("UserId :-"+ credential.getUserId());
          System.out.println("Pwd :-" +String.valueOf(credential.getPassword()));
          }
          catch(Exception  e){
                return ;
          }
        }
// Invoke the JSP to render, replace with the actual jsp name
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher("/_CredentialVault/jsp/html/CredentialVaultPortletView.jsp");
rd.include(request,response);

// or write to the response directly
//response.getWriter().println("CredentialVault#doView()");
}

private void  getActiveCredentilas(RenderRequest request ){
String slot = getSharedSlotId(request);
if (slot != null)
        {
              HttpFormBasedAuthCredential credential;
              try {
                    credential = (HttpFormBasedAuthCredential) cvs.getCredential(slot,CredentialTypes.HTTP_FORM_BASED_AUTH, buildCredentialConfigurationMap(), request);
                    //login to the resource
                    credential.login();
                    HttpURLConnection infoConn = credential.getAuthenticatedConnection("http://localhost:10039/Login/TestServlet");
                    InputStream is = infoConn.getInputStream();
                    //String info = readStringFromStream(is);
                    //credential.logout();
                    //request.setAttribute("result",info);
                 
              } catch (CredentialVaultException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
              }
               catch (Exception e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                    }
        }
}

private Map buildCredentialConfigurationMap()
{
   Map credentialDataMap = new HashMap();
   LinkedList list = new LinkedList();
   list.add("action=j_security_check");
   credentialDataMap.put(HttpFormBasedAuthCredential.KEY_FORM_DATA, list);
   credentialDataMap.put(HttpFormBasedAuthCredential.KEY_USE_AUTH_COOKIES, Boolean.TRUE);
   credentialDataMap.put(HttpFormBasedAuthCredential.KEY_LOGIN_URL, "http://localhost:10039/Login/j_security_check");
   credentialDataMap.put(HttpFormBasedAuthCredential.KEY_LOGOUT_URL, "http://localhost:10039/Login/j_security_check");
   credentialDataMap.put(HttpFormBasedAuthCredential.KEY_PASSWORD_ATTRIBUTE_NAME, "j_password");
   credentialDataMap.put(HttpFormBasedAuthCredential.KEY_USERID_ATTRIBUTE_NAME, "j_username");
   return credentialDataMap;
}

/**
* Serve up the <code>edit</code> mode.
*
* @see javax.portlet.GenericPortlet#doEdit(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
 // Set the MIME type for the render response
        response.setContentType(request.getResponseContentType());

        // Invoke the JSP to render
        PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher("EditCredentials.jsp");
        rd.include(request,response);
}

/**
* Serve up the <code>help</code> mode.
*
* @see javax.portlet.GenericPortlet#doHelp(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
protected void doHelp(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// TODO: auto-generated method stub
}

/**
* Process an action request.
*
* @see javax.portlet.Portlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
*/
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
try {
System.out.println("Entering ino processAction");

// Set userId/password text in the credential vault
String slotName   = getSharedSlotId(request);
if(slotName == null)
slotName=createSlot(request);
System.out.println("slotName="+slotName);
String userID   = request.getParameter("username");
String password = request.getParameter("password");
// save only if both parameters are set
if(slotName != null && userID!=null && password!=null && !userID.trim().equals("") && !password.trim().equals("")) {
cvs.setCredentialSecretUserPassword(slotName, userID,password.toCharArray(),request);

}

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

private String createSlot(ActionRequest request) throws Exception
{
   String resourceName = sharedSlotResourceName; //For shared slot resource name should be slot name
   ObjectID segmentID = cvs.getDefaultUserCredentialSegmentId();
   HashMap<String, String> descriptionsMap = new HashMap<String, String>();
   HashMap<String, String> keywordsMap = new HashMap<String, String>();
   int secretType = CredentialVaultService.SECRET_TYPE_USERID_STRING_PASSWORD_STRING;
   boolean bActive = true; //Active
   boolean bPrivate = true; //Portlet Private Slot
   CredentialSlotConfig slot=null;
   try
   {
   //Creating slot
       slot= cvs.createCredentialSlot(resourceName, segmentID,descriptionsMap, keywordsMap, secretType, bActive, bPrivate, request);
       System.out.println("New active slot created: " + slot);
   }
   catch(Exception e)
   {
       e.printStackTrace();
   }
   return slot.getSlotId();
}
private String getSharedSlotId(PortletRequest request)
{
   String slotId=null;
   try
   {
       for(Iterator it = cvs.getAccessibleSlots(request); it.hasNext();)
       {
           CredentialSlotConfig config = (CredentialSlotConfig)it.next();
           if(config.getResourceName().startsWith(sharedSlotResourceName))
           {
               slotId = config.getSlotId();
               return slotId;
           }
       }

   }
   catch(CredentialVaultException e)
   {
       System.out.println("Exception while retrieveing slot id " + e);
   }
   return slotId;
}

}


Edit Page JSP :- 
<%@page language="java"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="false"%>
<%@taglib uri="http://java.sun.com/portlet" prefix="portlet"%>
<%@taglib
uri="http://www.ibm.com/xmlns/prod/websphere/portal/v6.1/portlet-client-model"
prefix="portlet-client-model"%><portlet-client-model:init>
<portlet-client-model:require module="ibm.portal.xml.*" />
<portlet-client-model:require module="ibm.portal.portlet.*" />
</portlet-client-model:init>

<portlet:defineObjects />
<form name="f1" method="post" action="<portlet:actionURL/>" id="f1">
                <table>
                    <tr>
                        <td class="f1_label">User Name :</td><td><input type="text" name="username" value="" />
                        </td>
                    </tr>
                    <tr>
                        <td class="f1_label">Password  :</td><td><input type="password" name="password" value=""  />
                        </td>
                    </tr>
                    <tr>
                        <td>
                        <input type="submit" name="login" value="Store Credentials" style="font-size:18px; " />
                        </td>
                    </tr>
                </table>
            </form>

<p>Place content here.</p>









Thursday, 20 March 2014

Jaxb object to xml convertion

//Pass the object class which should be converted to xml and pass base xml class to JAXBContext

public static String convertObjectToXML(GetResponse  object) throws JAXBException {
String sl_XML =null;
StringWriter stringWriter = new StringWriter();
try {
JAXBContext jaxbContext = JAXBContext
.newInstance(GetResponse.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(object, stringWriter);
} catch (JAXBException e) {
throw new JAXBException(e);
}
sl_XML = stringWriter.getBuffer().toString();


return sl_XML;
}

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...