Quantcast
Channel: SCN : All Content - Web Dynpro Java
Viewing all articles
Browse latest Browse all 1288

Roles, Groups and User information from the Enterprise portal 7.0 using Webdynpro JAVA

$
0
0

Hello Friends,

 

The purpose of this document is to explain

 

How to get Roles, Groups and User information from the Enterprise portal 7.0 and Generate 3 different file (Role.txt, Groups.txt and Users.txt). After creation of these 3 files will receives a mail.

 

For Example

Roles: name of the role

Which groups the role has

Which users the role has

2.JPG

3.JPG

Groups: name of the group

Which users the group has

Which roles the group has

4.JPG

5.JPG

Users: name of the user

Which groups the user has

Which roles the user is has

6.JPG

7.JPG

 

WebDynpro JAVA Application Development Steps:

UI in View:-

                         9.JPG         

Context in Component Controller and View

                         8.JPG

Methods in View

                         10.JPG

 

Method in Component Controller:-

                           11.JPG

 

Code in View:-

 

package sap.corp.view.v_generateugrfile.com;

 

import sap.corp.view.v_generateugrfile.com.wdp.IPrivateV_GenerateUGRFile;

 

import java.util.Properties;

 

import javax.activation.DataSource;

 

import javax.activation.FileDataSource;

 

import java.text.SimpleDateFormat;

 

import java.io.BufferedWriter;

 

import java.io.File;

 

import java.io.FileWriter;

 

import java.io.IOException;

 

import java.util.Date;

 

import javax.activation.DataHandler;

 

import java.text.DecimalFormat;

 

import java.text.NumberFormat;

 

import javax.mail.BodyPart;

 

import javax.mail.Message;

 

import javax.mail.MessagingException;

 

import javax.mail.Multipart;

 

import javax.mail.Session;

 

import javax.mail.Transport;

 

import javax.mail.internet.InternetAddress;

 

import javax.mail.internet.MimeBodyPart;

 

import javax.mail.internet.MimeMessage;

 

import javax.mail.internet.MimeMultipart;

 

import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;

 

import com.sap.tc.webdynpro.progmodel.repository.IWDControllerInfo;

 

import com.sap.tc.webdynpro.progmodel.repository.IWDEventHandlerInfo;

 

import com.sap.tc.webdynpro.services.session.api.IWDConfirmationDialog;

 

publicclass V_GenerateUGRFile

 

  /**

   *Logginglocation.

   */

  privatestaticfinal com.sap.tc.logging.Location logger =

  com.sap.tc.logging.Location.getLocation(V_GenerateUGRFile.class);

  static

 

   //@@begin id

  String id = "$Id$";

   //@@end

  com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);

 

  /**

   *PrivateaccesstothegeneratedWebDynprocounterpart

   *forthiscontrollerclass.  </p>

   *

   *Use<code>wdThis</code>togaintypedaccesstothecontext,

   *totriggernavigationviaoutboundplugs,togetandenable/disable

   *actions,firedeclaredevents,andaccessusedcontrollersand/or

   *componentusages.

   *

   *@seesap.corp.view.v_generateugrfile.com.wdp.IPrivateV_GenerateUGRFileformoredetails

   */

  privatefinal IPrivateV_GenerateUGRFile wdThis;

  /**

   *Rootnodeofthiscontroller'scontext.</p>

   *

   *Providestypedaccessnotonlytotheelementsoftherootnode

   *butalsotoallnodesinthecontext(methodsnode<i>XYZ</i>())

   *andtheircurrentlyselectedelement(methodscurrent<i>XYZ</i>Element()).

   *Italsofacilitatesthecreationofnewelementsforallnodes

   *(methodscreate<i>XYZ</i>Element()).</p>

   *

   *@seesap.corp.view.v_generateugrfile.com.wdp.IPrivateV_GenerateUGRFile.IContextNodeformoredetails.

   */

  privatefinal IPrivateV_GenerateUGRFile.IContextNode wdContext;

  /**

   *Ashortcutfor<code>wdThis.wdGetAPI()</code>.</p>

   *

   *RepresentsthegenericAPIofthegenericWebDynprocounterpart

   *forthiscontroller.</p>

   */

  privatefinal com.sap.tc.webdynpro.progmodel.api.IWDViewController wdControllerAPI;

  /**

   *Ashortcutfor<code>wdThis.wdGetAPI().getComponent()</code>.</p>

   *

   *RepresentsthegenericAPIoftheWebDynprocomponentthiscontroller

   *belongsto.Canbeusedtoaccessthemessagemanager,thewindowmanager,

   *toadd/removeeventhandlersandsoon.</p>

   */

  privatefinal com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;

  public V_GenerateUGRFile(IPrivateV_GenerateUGRFile wdThis)

 

   this.wdThis = wdThis;

   this.wdContext = wdThis.wdGetContext();

   this.wdControllerAPI = wdThis.wdGetAPI();

   this.wdComponentAPI = wdThis.wdGetAPI().getComponent();

 

  //@@begin javadoc:wdDoInit()

  /**Hookmethodcalledtoinitializecontroller.*/

  //@@end

  publicvoid wdDoInit()

 

   //@@begin wdDoInit()

   //@@end

 

  //@@begin javadoc:wdDoExit()

  /**Hookmethodcalledtocleanupcontroller.*/

  //@@end

  publicvoid wdDoExit()

 

   //@@begin wdDoExit()

   //@@end

 

  //@@begin javadoc:wdDoModifyView

  /**

   *Hookmethodcalledtomodifyaviewjustbeforerendering.

   *Thismethodconceptuallybelongstotheviewitself,nottothe

   *controller(cf.MVCpattern).

   *Itismadestatictodiscourageawayofprogrammingthat

   *routinelystoresreferencestoUIelementsininstancefields

   *foraccessbytheviewcontroller'seventhandlers,andsoon.

   *TheWebDynproprogrammingmodelrecommendsthatUIelementscan

   *onlybeaccessedbycodeexecutedwithinthecalltothishookmethod.

   *

   *@paramwdThisGeneratedprivateinterfaceoftheview'scontroller,as

   *   providedbyWebDynpro.Providesaccesstotheviewcontroller's

   *   outgoingcontrollerusages,etc.

   *@paramwdContextGeneratedinterfaceoftheview'scontext,asprovided

   *   byWebDynpro.Providesaccesstotheview'sdata.

   *@paramviewTheview'sgenericAPI,asprovidedbyWebDynpro.

   *   ProvidesaccesstoUIelements.

   *@paramfirstTimeIndicateswhetherthehookiscalledforthefirsttime

   *   duringthelifetimeoftheview.

   */

  //@@end

  publicstaticvoid wdDoModifyView(IPrivateV_GenerateUGRFile wdThis, IPrivateV_GenerateUGRFile.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)

 

   //@@begin wdDoModifyView

   //@@end

 

  //@@begin javadoc:sendMail()

  /**Declaredmethod.*/

  //@@end

  publicvoid sendMail( java.lang.String bodyText, java.lang.String subject )

 

   //@@begin sendMail()

 

Properties properties = new Properties();

  // Setup mail server

properties.setProperty("mail.smtp.host", host);

  // Get the default Session object.

Session session = Session.getInstance(properties, null);

  try{

  // Create a default MimeMessage object.

MimeMessage message = new MimeMessage(session);

  // Set From: header field of the header.

message.setFrom(new InternetAddress(emailFrom));

  // Set To: header field of the header.

message.setRecipient(Message.RecipientType.TO,new InternetAddress(emailTO));

  // Set Subject: header field

 

  // Now set the actual message

 

  // Send message

 

} catch (MessagingException mex) {

 

wdComponentAPI.getMessageManager().reportException("Exception In sendMail():"+mex.getMessage(), false);

 

   //@@end

 

  //@@begin javadoc:sendEmailAttachment()

  /**Declaredmethod.*/

  //@@end

  publicvoid sendEmailAttachment( java.lang.String bodytxt, java.lang.String subject )

 

   //@@begin sendEmailAttachment()

 

  // Setup mail server

properties.setProperty("mail.smtp.host", host);

  // Get the default Session object.

 

  try{

  // Create a default MimeMessage object.

MimeMessage message = new MimeMessage(session);

  // Set From: header field of the header.

message.setFrom(new InternetAddress(emailFrom));

  // Set To: header field of the header.

message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTO));

  // Set Subject: header field

message.setSubject("This is the Subject Line!");

  // Create the message part

BodyPart messageBodyPart = new MimeBodyPart();

  // Fill the message

messageBodyPart.setText("This is message body");

  // Create a multipar message

Multipart multipart = new MimeMultipart();

  // Set text message part

 

  // Part two is attachment

messageBodyPart = new MimeBodyPart();

  // String filename = "D://Work//error.log"

DataSource source = new FileDataSource(errorLog);

messageBodyPart.setDataHandler(new DataHandler(source));

 

  // Send the complete message parts

 

  // Send message

 

} catch (MessagingException mex) {

 

wdComponentAPI.getMessageManager().reportException("Exception In sendEmailAttachment():"+mex.getMessage(), false);

 

   //@@end

 

  //@@begin javadoc:onActiongenerateUGRfile(ServerEvent)

  /**Declaredvalidatingeventhandler.*/

  //@@end

  publicvoid onActiongenerateUGRfile(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

 

   //@@begin onActiongenerateUGRfile(ServerEvent)

 

if(wdContext.currentContextElement().getEmail()==null ||(emailTO == null || emailTO.trim().length() == 0)){

wdComponentAPI.getMessageManager().reportException("Please set the E-Mail before Before Start the Script",true);

} else

 

IWDEventHandlerInfo evtHndlr = controllerInfo.findInEventHandlers("Start_Script_Canceled");

String confTextBody = "You are about to Create New" +"sqlStatement"+ "File, Are you sure?";

IWDConfirmationDialog confDialog = wdComponentAPI.getWindowManager().createConfirmationWindow(confTextBody,evtHndlr,"No, Cancel");

evtHndlr = controllerInfo.findInEventHandlers("Start_Script_Confirmed");

confDialog.addChoice(evtHndlr, "Yes, Confirm");

confDialog.setTitle("Start_Script_Confirmed Confirmation?");

 

   //@@end

 

  //@@begin javadoc:onActionsetEmail(ServerEvent)

  /**Declaredvalidatingeventhandler.*/

  //@@end

  publicvoid onActionsetEmail(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

 

   //@@begin onActionsetEmail(ServerEvent)

 

if (emailTO == null || emailTO.trim().length() == 0) {

wdComponentAPI.getMessageManager().reportException("Please Set the Email",false);

} else {

if (emailTO.matches("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)"+"@sap.com")) {

wdComponentAPI.getMessageManager().reportSuccess("Email Successfully Updated.");

} else {

wdComponentAPI.getMessageManager().reportWarning("Email Address is not Valid.");

 

   //@@end

 

  //@@begin javadoc:Start_Script_Canceled(ServerEvent)

  /**Declaredvalidatingeventhandler.*/

  //@@end

  publicvoid Start_Script_Canceled(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

 

   //@@begin Start_Script_Canceled(ServerEvent)

   //@@end

 

  //@@begin javadoc:Crawl_Resources(ServerEvent)

  /**Declaredvalidatingeventhandler.*/

  //@@end

  publicvoid Crawl_Resources(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

 

   //@@begin Crawl_Resources(ServerEvent)

BufferedWriter logFile =null;

 

 

NumberFormat formatter = new DecimalFormat("#0.00000");

long endTime = System.currentTimeMillis();

String mailSub = "Generated Users,Group & Roles Files Script";

String mailBody = "Dear User,\n\n"

+ "New Script has saved under path c:\\Users_Group_Roles\\ \n\n"

+ "Total Number of Users in Portal:" +wdContext.nodeUserTable().size()+"\n"

+ "Total Number of Groups in Portal:"+wdContext.nodeGroupTable().size()+"\n"

+ "Total Number of Roles in Portal:"+wdContext.nodeRoleTable().size()+"\n\n"

+"Total Processing Time is: " + formatter.format((endTime - startTime) / 1000d) + " seconds\n\n"

+ "Note: This is an automated notification, please do not reply.";

 

//long endTime = System.currentTimeMillis();

//NumberFormat formatter = new DecimalFormat("#0.00000");

wdComponentAPI.getMessageManager().reportSuccess("Total Processing Time is: " + formatter.format((endTime - startTime) / 1000d) + " seconds");

   //@@end

 

  //@@begin javadoc:Start_Script_Confirmed(ServerEvent)

  /**Declaredvalidatingeventhandler.*/

  //@@end

  publicvoid Start_Script_Confirmed(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

 

   //@@begin Start_Script_Confirmed(ServerEvent)

try {

 

IWDEventHandlerInfo evtHndlr = controllerInfo.findInEventHandlers("Crawl_Resources");

String confTextBody = "New Import Script has created Successfully.\n\n"

+"After you select OK the script will begin the script will take approximate 2 hours or more to complete.\n\n"

+"When it is completed you will receive an email.";

IWDConfirmationDialog confDialog = wdComponentAPI.getWindowManager().createConfirmationWindow(confTextBody,evtHndlr,"Ok");

confDialog.setTitle("Start Script ?");

 

catch (Exception um) {

// TODO Auto-generated catch block

 

wdComponentAPI.getMessageManager().reportException("Exception In Start_Script_Confirmed():"+um.getMessage(), false);

 

   //@@end

 

  /*

 

  //@@begin others

 

String host = "sap.com";

String emailFrom = "tech.support@sap.com";

File errorLog = new File("c:\\Users_Group_Roles\\error_"+ new SimpleDateFormat("MM-dd-yyyy HHmm").format(new Date())+ ".log");

IWDMessageManager msgMgr = null;

long startTime = System.currentTimeMillis();

  //@@end

 

 

 

Code in Component Controller:-

 

 

package sap.corp.comp.co_generateugrfile.com;

 

import java.io.BufferedWriter;

 

import java.io.File;

 

import java.io.FileWriter;

 

import java.io.IOException;

 

import java.text.SimpleDateFormat;

 

import java.util.Date;

 

import java.util.Iterator;

 

import com.sap.security.api.IGroup;

 

import com.sap.security.api.IGroupFactory;

 

import com.sap.security.api.IGroupSearchFilter;

 

import com.sap.security.api.IRole;

 

import com.sap.security.api.IRoleFactory;

 

import com.sap.security.api.IRoleSearchFilter;

 

import com.sap.security.api.ISearchAttribute;

 

import com.sap.security.api.ISearchResult;

 

import com.sap.security.api.IUser;

 

import com.sap.security.api.IUserFactory;

 

import com.sap.security.api.IUserSearchFilter;

 

import com.sap.security.api.UMFactory;

 

import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;

 

import sap.corp.comp.co_generateugrfile.com.wdp.IPrivateCO_GenerateUGRFile;

 

publicclass CO_GenerateUGRFile

 

  /**

   *Logginglocation.

   */

  privatestaticfinal com.sap.tc.logging.Location logger =

  com.sap.tc.logging.Location.getLocation(CO_GenerateUGRFile.class);

  static

 

   //@@begin id

  String id = "$Id$";

   //@@end

  com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);

 

  /**

   *PrivateaccesstothegeneratedWebDynprocounterpart

   *forthiscontrollerclass.  </p>

   *

   *Use<code>wdThis</code>togaintypedaccesstothecontext,

   *totriggernavigationviaoutboundplugs,togetandenable/disable

   *actions,firedeclaredevents,andaccessusedcontrollersand/or

   *componentusages.

   *

   *@seesap.corp.comp.co_generateugrfile.com.wdp.IPrivateCO_GenerateUGRFileformoredetails

   */

  privatefinal IPrivateCO_GenerateUGRFile wdThis;

  /**

   *Rootnodeofthiscontroller'scontext.</p>

   *

   *Providestypedaccessnotonlytotheelementsoftherootnode

   *butalsotoallnodesinthecontext(methodsnode<i>XYZ</i>())

   *andtheircurrentlyselectedelement(methodscurrent<i>XYZ</i>Element()).

   *Italsofacilitatesthecreationofnewelementsforallnodes

   *(methodscreate<i>XYZ</i>Element()).</p>

   *

   *@seesap.corp.comp.co_generateugrfile.com.wdp.IPrivateCO_GenerateUGRFile.IContextNodeformoredetails.

   */

  privatefinal IPrivateCO_GenerateUGRFile.IContextNode wdContext;

  /**

   *Ashortcutfor<code>wdThis.wdGetAPI()</code>.</p>

   *

   *RepresentsthegenericAPIofthegenericWebDynprocounterpart

   *forthiscontroller.</p>

   */

  privatefinal com.sap.tc.webdynpro.progmodel.api.IWDComponent wdControllerAPI;

  /**

   *Ashortcutfor<code>wdThis.wdGetAPI().getComponent()</code>.</p>

   *

   *RepresentsthegenericAPIoftheWebDynprocomponentthiscontroller

   *belongsto.Canbeusedtoaccessthemessagemanager,thewindowmanager,

   *toadd/removeeventhandlersandsoon.</p>

   */

  privatefinal com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;

  public CO_GenerateUGRFile(IPrivateCO_GenerateUGRFile wdThis)

 

   this.wdThis = wdThis;

   this.wdContext = wdThis.wdGetContext();

   this.wdControllerAPI = wdThis.wdGetAPI();

   this.wdComponentAPI = wdThis.wdGetAPI().getComponent();

 

  //@@begin javadoc:wdDoInit()

  /**Hookmethodcalledtoinitializecontroller.*/

  //@@end

  publicvoid wdDoInit()

 

   //@@begin wdDoInit()

   //@@end

 

  //@@begin javadoc:wdDoExit()

  /**Hookmethodcalledtocleanupcontroller.*/

  //@@end

  publicvoid wdDoExit()

 

   //@@begin wdDoExit()

   //@@end

 

  //@@begin javadoc:wdDoPostProcessing()

  /**

   *Hookcalledtohandledataretrievalerrorsbeforerendering.

   *

   *AfterdoModifyView(),theWebDynproFrameworkgetsallcontextdataneeded

   *forrenderingbyvalidatingthecontexts(whichinturncallsthesupply

   *functionsandsupplyingrelationroles).Inthishook,theapplication

   *shouldhandletheerrorswhichoccurredduringvalidationofthecontexts.

   *

   *Usingpreorderdepth-firsttraversal,thishookiscalledforallcomponent

   *controllersstartingwiththecurrentrootcomponent.

   *

   *Permittedoperations:

   *-Flushingmodelqueue

   *-Creatingmessages

   *-Readingcontextandmodeldata

   *

   *Forbiddenoperations:

   *-Invalidatingmodeldata

   *-Manipulatingthecontext

   *-Firingoutboundplugs

   *-Creatingcomponents

   *-...

   *

   *@paramisCurrentRoottrueifthisistherootofthecurrentrequest

   */

  //@@end

  publicvoid wdDoPostProcessing(boolean isCurrentRoot)

 

   //@@begin wdDoPostProcessing()

   //@@end

 

  //@@begin javadoc:wdDoBeforeNavigation()

  /**

   *Hookbeforethenavigationphasestarts.

   *

   *Thishookallowsyoutoflushthemodelqueueandhandleany

   *errorsthatoccur.Firingoutboundplugsisallowedinthishook.

   *

   *Usingpreorderdepth-firsttraversal,thishookiscalledforallcomponent

   *controllersstartingwiththecurrentrootcomponent.

   *

   *@paramisCurrentRoottrueifthisistherootofthecurrentrequest

   */

  //@@end

  publicvoid wdDoBeforeNavigation(boolean isCurrentRoot)

 

   //@@begin wdDoBeforeNavigation()

   //@@end

 

  //@@begin javadoc:wdDoApplicationStateChange()

  /**

   *Hookthatinformstheapplicationaboutastatechange.

   *<p>

   *Thishookiscallede.g.totelltheapplicationthatwillbe

   *<ul>

   *  <li>leftviaasuspendplugandthereforeshouldgointoasuspend/sleep

   *   modewithminimalneedofresources.errorsthatoccur.Firing

   *   outboundplugsisallowedinthishook.

   *  <li>leftduetoatimeoutandcouldwriteit'sstatetoadatabaseifthe

   *   usercomesbacklateron

   *</ul>

   *

   *TheconcretereasonisavailableviaIWDApplicationStateChangeInfo

   *<p>

   *<b>Important</b>:Thishookiscalledforthetoplevelcomponentonly!

   *

   *@paramstateChangeInfocontainstheinformationaboutthenatureofthestatechange

   *@paramstateChangeReturnallowstheapplicationtoaskforadifferentstatechange.

   *   Theframeworkisallowedtoignoreitconsideringi.e.thecurrentresourcessituation.

   */

  //@@end

  publicvoid wdDoApplicationStateChange(com.sap.tc.webdynpro.progmodel.api.IWDApplicationStateChangeInfo stateChangeInfo, com.sap.tc.webdynpro.progmodel.api.IWDApplicationStateChangeReturn stateChangeReturn)

 

   //@@begin wdDoApplicationStateChange()

   //@@end

 

  //@@begin javadoc:generate_User_Group_Role_Scriptfile()

  /**Declaredmethod.*/

  //@@end

  publicvoid generate_User_Group_Role_Scriptfile( java.io.BufferedWriter logFile )

 

   //@@begin generate_User_Group_Role_Scriptfile()

 

  String schCriteriaText ="*";

if (schCriteriaText == null || schCriteriaText.trim().length() == 0) {

schCriteriaText = "*";

 

  try

 

groupFilt.setUniqueName(schCriteriaText.trim(), ISearchAttribute.LIKE_OPERATOR, false);

 

//String grpId = "";

//String grpDesc = "";

//String grpRole = "";

 

if (result.size() > 0)

 

if(result.getState() == ISearchResult.SEARCH_RESULT_OK)

 

File dir = new File("c:\\Users_Group_Roles");

File file = new File("c:\\Users_Group_Roles\\"+"Groups"+"_"+ new SimpleDateFormat("MM-dd-yyyy HHmm").format(new Date())+ ".log");

FileWriter fw = new FileWriter(file,true);

logFile = new BufferedWriter(fw);

while(result.hasNext())

 

StringBuffer getGroupID =new StringBuffer();

StringBuffer getGroupDesc =new StringBuffer();

StringBuffer getGroupUser =new StringBuffer();

StringBuffer getGroupRole=new StringBuffer();

 

//grpTable.setDisplayName(thisGroup.getDisplayName());

 

//getGroupDesc.append(thisGroup.getDescription());

 

if(grpDesc!=null)

 

}else{

getGroupDesc.append("");

 

//wdComponentAPI.getMessageManager().reportSuccess("---getGroupID----:"+getGroupID);

//wdComponentAPI.getMessageManager().reportSuccess("---getGroupDesc----:"+getGroupDesc);

 

//grpTable.setUniqueID(thisGroup.getUniqueID());

 

//Iterator itrUserName = thisGroup.getUserMembers(true);

Iterator itrUserName = thisGroup.getUserMembers(true);

Iterator itrRoleName = thisGroup.getRoles(true);

while(itrUserName.hasNext())

 

//grpTable.setUserInfo(itrUserName.next().toString());

 

int lindex=str.lastIndexOf(":");

 

getGroupUser.append(str+",");

//getGroupUser.append(itrUserName.next().toString()+",");

//wdComponentAPI.getMessageManager().reportSuccess("---getGroupUser----:"+getGroupUser);

 

int GroupUserindex=getGroupUser.lastIndexOf(",");

String grpUserBuffer="";

String grpUser = "";

if(GroupUserindex!=-1)

 

while(itrRoleName.hasNext())

 

//grpTable.setRoleInfo(irole.getUniqueName());

if(!irole.getUniqueName().equalsIgnoreCase(""))

 

int lindex=str.lastIndexOf("/rl");

 

//wdComponentAPI.getMessageManager().reportSuccess("---str----:"+str);

getGroupRole.append(str+",");

//getGroupRole.append(irole.getUniqueName()+",");

 

//StringBuffer buffer=getGroupRole;

int GroupRoleindex=getGroupRole.lastIndexOf(",");

String grpRoleBuffer="";

if(GroupRoleindex!=-1)

 

//wdComponentAPI.getMessageManager().reportSuccess("---role----:"+index);

//wdContext.nodeGroupTable().addElement(grpTable);

 

String sqlGroupStatement = "";

 

String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.

 

sqlGroupStatement += "INSERT INTO TableName(GID, DESCRIPTION) VALUES ";

sqlGroupStatement += "('"+getGroupID+ "', '"+getGroupDesc+"');"+newLine+"";

 

String delimiter = ",";

if(grpUserBuffer.equalsIgnoreCase(""))

 

}else

 

for(int i=0; i<groupUserParts.length;i++)

 

//grpUser = parts[i];

//wdComponentAPI.getMessageManager().reportSuccess("---grpUser----:"+grpUser);

//wdComponentAPI.getMessageManager().reportSuccess("---parts----:"+parts[i].length());

sqlGroupStatement += "INSERT INTO TableName(GID, UID) VALUES";

sqlGroupStatement += "('"+getGroupID+"', '"+groupUserParts[i]+"');"+newLine+"";

 

if(grpRoleBuffer.equalsIgnoreCase(""))

 

else

 

for(int i=0; i<roleParts.length;i++)

 

sqlGroupStatement += "INSERT INTO TableName(GID, RID) VALUES ";

sqlGroupStatement += "('"+ getGroupID + "', '"+roleParts[i]+ "' );"+newLine+"";

 

long srtTime = System.currentTimeMillis();

if (!dir.exists())

 

try

 

//logFile.write("[group]"+newLine); 

 

//wdThis.generate_User_Group_Role_Scriptfile(logFile);

 

catch(IOException ex)

 

wdComponentAPI.getMessageManager().reportException("Exception In Roles():"+ex.getMessage(), false);

 

}else

 

msgMgr.reportWarning("No element found.");

 

roleSrcFilter.setUniqueName(schCriteriaText.trim(),ISearchAttribute.LIKE_OPERATOR,false);

 

if (srhResults.size() > 0){

if(srhResults.getState() == ISearchResult.SEARCH_RESULT_OK) {

File dir = new File("c:\\Users_Group_Roles");

File file = new File("c:\\Users_Group_Roles\\"+"Roles"+"_"+ new SimpleDateFormat("MM-dd-yyyy HHmm").format(new Date())+ ".log");

FileWriter fw = new FileWriter(file,true);

logFile = new BufferedWriter(fw);

while(srhResults.hasNext()) {

StringBuffer getRoleID=new StringBuffer();

StringBuffer getRoleDesc=new StringBuffer();

StringBuffer getRoleGroup =new StringBuffer();

StringBuffer getRoleUser =new StringBuffer();

 

//getRoleDesc.append(thisRole.getDescription());

 

if(roleDesc!=null){

 

}else{

getRoleDesc.append("");

 

Iterator itrUserName = thisRole.getUserMembers(true);

Iterator itrGroupName = thisRole.getGroupMembers(true);

while(itrUserName.hasNext())

 

//rTable.setUserInfo(itrUserName.next().toString());

 

int lindex=str.lastIndexOf(":");

 

getRoleUser.append(str+",");

//getRoleUser.append(itrUserName.next().toString()+",");

//wdComponentAPI.getMessageManager().reportSuccess("---itrUserName.hasNext()----:"+itrUserName.next());

 

int roleUserindex=getRoleUser.lastIndexOf(",");

String roleUserBuffer="";

if(roleUserindex!=-1)

 

while(itrGroupName.hasNext())

 

  //rTable.setGroupInfo(itrGroupName.next().toString());

//getRoleGroup.append(itrGroupName.next().toString()+",");

 

int lindex=str.lastIndexOf(":");

 

getRoleGroup.append(str+",");

//wdComponentAPI.getMessageManager().reportSuccess("---itrGroupName.hasNext()----:"+itrGroupName.next());

 

int roleGroupindex=getRoleGroup.lastIndexOf(",");

String roleGroupBuffer="";

if(roleGroupindex!=-1)

 

//wdContext.nodeRoleTable().addElement(rTable);

String sqlRoleStatement = "";

 

String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.

 

sqlRoleStatement += "INSERT INTO TableName(RID, DESCRIPTION) VALUES";

sqlRoleStatement += "('"+ getRoleID +"', '"+ getRoleDesc +"');"+newLine+"";

 

String delimiter = ",";

if(roleGroupBuffer.equalsIgnoreCase(""))

 

}else

 

for(int i=0; i<roleGroupParts.length;i++)

 

sqlRoleStatement += "INSERT INTO TableName(RID, GID) VALUES";

sqlRoleStatement += "('"+getRoleID+ "', '"+roleGroupParts[i]+ "' );"+newLine+"";

 

if(roleUserBuffer.equalsIgnoreCase(""))

 

}else{

 

for(int i=0; i<roleUserParts.length;i++)

 

sqlRoleStatement += "INSERT INTO TableName(RID, UID) VALUES ";

sqlRoleStatement += "('"+ getRoleID + "', '"+roleUserParts[i]+ "' );"+newLine+"";

 

long srtTime = System.currentTimeMillis();

if (!dir.exists())

 

try

 

//logFile.write("[role]"+newLine); 

 

//wdThis.generate_User_Group_Role_Scriptfile(logFile);

 

catch(IOException ex)

 

wdComponentAPI.getMessageManager().reportException("Exception In Roles():"+ex.getMessage(), false);

 

} else {

wdComponentAPI.getMessageManager().reportWarning("No element found.");

 

usrSrchFilter.setUniqueName(schCriteriaText.trim(),ISearchAttribute.LIKE_OPERATOR,false);

 

if (srchResluts.size() >0){

if(srchResluts.getState() == ISearchResult.SEARCH_RESULT_OK) {

File dir = new File("c:\\Users_Group_Roles");

File file = new File("c:\\Users_Group_Roles\\"+"User"+"_"+ new SimpleDateFormat("MM-dd-yyyy HHmm").format(new Date())+ ".log");

FileWriter fw = new FileWriter(file,true);

logFile = new BufferedWriter(fw);

while (srchResluts.hasNext()){

StringBuffer getuserID =new StringBuffer();

StringBuffer getlastName =new StringBuffer();

StringBuffer getfirstName =new StringBuffer();

StringBuffer getemailID =new StringBuffer();

StringBuffer getRoleInfo=new StringBuffer();

StringBuffer getGroupInfo =new StringBuffer();

 

if(lastName!=null){

 

}else{

getlastName.append("");

 

if(firstName!=null){

 

}else{

getfirstName.append("");

 

if(eMail!=null){

 

}else{

getemailID.append("");

 

//String getLogonID = sapUser.getUserAccounts()[0].getLogonUid();

//usrTable.setUserNames(sapUser.getLastName()+','+" "+sapUser.getFirstName());

//wdComponentAPI.getMessageManager().reportSuccess("---UserID----:"+getLogonID);

Iterator itrRoleName = sapUser.getRoles(true);

Iterator itrGroupName = sapUser.getParentGroups(true);

while(itrRoleName.hasNext())

 

//IRole roleId = itrRoleName.next();

 

//wdComponentAPI.getMessageManager().reportSuccess("---roleId----:"+irole.getUniqueName());

//wdComponentAPI.getMessageManager().reportSuccess("---itrRoleName----:"+irole.getDescription());

//String roletext = roleId.getUniqueName();

//usrTable.setRoleInfo(irole.getUniqueName());

//wdComponentAPI.getMessageManager().reportSuccess("---roleId----:"+irole.getUniqueID());

 

int lindex=str.lastIndexOf("/rl");

 

//wdComponentAPI.getMessageManager().reportSuccess("---str----:"+str);

getRoleInfo.append(str+",");

//getRoleInfo.append(irole.getUniqueName()+",");

// wdComponentAPI.getMessageManager().reportSuccess("---roleId----:"+getRoleInfo);

 

int userRoleindex=getRoleInfo.lastIndexOf(",");

String userRoleBuffer="";

if(userRoleindex!=-1)

 

while(itrGroupName.hasNext())

 

//usrTable.setGroupInfo(itrGroupName.next().toString());

//getGroupInfo.append(itrGroupName.next().toString()+",");

 

int lindex=str.lastIndexOf(":");

 

getGroupInfo.append(str+",");

//wdComponentAPI.getMessageManager().reportSuccess("---itrGroupName.hasNext()----:"+getGroupInfo);

 

int userGroupindex=getGroupInfo.lastIndexOf(",");

String userGroupBuffer="";

if(userGroupindex!=-1)

 

String sqlUserStatement = "";

 

String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.

 

sqlUserStatement += "INSERT INTO TableName(UID, LASTNAME, FIRSTNAME, EMAIL) VALUES ";

sqlUserStatement += "('"+ getuserID +"', '"+ getlastName + "', '"+ getfirstName + "', '"+ getemailID + "');"+newLine+"";

 

String delimiter = ",";

if(userRoleBuffer.equalsIgnoreCase(""))

 

}else{

 

for(int i=0; i<userRoleParts.length;i++)

 

sqlUserStatement += "INSERT INTO TableName(UID, GID) VALUES";

sqlUserStatement += "('"+ getuserID + "', '"+ userRoleParts[i] + "' );"+newLine+"";

 

if(userGroupBuffer.equalsIgnoreCase(""))

 

}else{

 

for(int i=0; i<userGroupParts.length;i++)

 

sqlUserStatement += "INSERT INTO TableName(UID, RID) VALUES ";

sqlUserStatement += "('"+ getuserID + "', '"+ userGroupParts[i] + "' );"+newLine+"";

 

//wdComponentAPI.getMessageManager().reportSuccess("---sqlStatement----:"+sqlStatement);

long srtTime = System.currentTimeMillis();

if (!dir.exists())

 

try

 

// logFile.write("[User]"+newLine);

 

//wdThis.generate_User_Group_Role_Scriptfile(logFile);

 

catch(IOException ex)

 

wdComponentAPI.getMessageManager().reportException("Exception In Users:"+ex.getMessage(), false);

 

} else {

wdComponentAPI.getMessageManager().reportWarning("No element found.");

 

//wdComponentAPI.getMessageManager().reportSuccess("---Group Node Size----:"+wdContext.nodeGroupTable().size());

//wdComponentAPI.getMessageManager().reportSuccess("---Role Node Size----:"+wdContext.nodeRoleTable().size());

//wdComponentAPI.getMessageManager().reportSuccess("---User Node Size----:"+wdContext.nodeUserTable().size());

}catch(Exception ex){

//wdComponentAPI.getMessageManager().reportSuccess("---Exception----:"+ex.getLocalizedMessage());

 

   //@@end

 

  /*

 

  //@@begin others

  IWDMessageManager msgMgr = null;

 

 



Finally the OUTPUT will generate like this

USER Example

 

[User]

uid=AAAAAA

last_name=B

first_name=A

email_address=AAAAAA@sap.com

role=

group=New_Portal User;Guest;


 

 

GROUP Example

 

[group]

gid=10

gdesc=xyz

user=Vijay,Ram.

role=??

 

Roles Example

 

[role]

rid=Administrator

rdesc=Administrator

user=Vijay,ram

group=Administrator

 

 

After creation of these 3 files will receives a mail


For Example:-

12.JPG



Thank you


Regards

Vijay Kalluri


Viewing all articles
Browse latest Browse all 1288

Trending Articles