Tuesday, December 17, 2013
How to Automatically Refresh the View Object of the View Accessor
If you need to ensure that your view accessor always queries the latest data from the lookup table, you can set the Auto Refresh property on the destination view object. This property allows the view object instance to refresh itself after a change in the database. The typical use case is when you define a view accessor for the destination view object.
For example, assume that an LOV displays a list of zip codes that is managed in read-only fashion by a database administrator. After the administrator adds a new zip code as a row to the database, the shared application module detects a time when there are no outstanding requests and determines that a pending notification exists for the view instance that access the list of zip codes; at that point, the view object refreshes the data and all future requests will see the new zip code.
To enable auto-refresh for a view instance of a shared application module:
#In the Application Navigator, double-click the view object that you want to receive database change notifications.
#In the overview editor, click the General navigation tab.
#In the Property Inspector expand the Tuning section, and select True for the Auto Refresh property.
Source: http://docs.oracle.com/cd/E16162_01/web.1112/e16182/bclookups.htm#CIHCHGIA
For example, assume that an LOV displays a list of zip codes that is managed in read-only fashion by a database administrator. After the administrator adds a new zip code as a row to the database, the shared application module detects a time when there are no outstanding requests and determines that a pending notification exists for the view instance that access the list of zip codes; at that point, the view object refreshes the data and all future requests will see the new zip code.
To enable auto-refresh for a view instance of a shared application module:
#In the Application Navigator, double-click the view object that you want to receive database change notifications.
#In the overview editor, click the General navigation tab.
#In the Property Inspector expand the Tuning section, and select True for the Auto Refresh property.
Source: http://docs.oracle.com/cd/E16162_01/web.1112/e16182/bclookups.htm#CIHCHGIA
Thursday, December 5, 2013
ADF Code Snippets
Code to get AppModule in Java Bean class
To implement resolvEDIC method
public Object resolvElDC(String data) {
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, "#{data." + data + ".dataProvider}", Object.class);
return valueExp.getValue(elContext);
}
Use this in code to get Application Module Impl class
AppModuleAMImpl am =
(AppModuleAMImpl)resolvElDC("AppModuleAMDataControl");
Code to show FacesMessege in page
FacesMessage message = new FacesMessage("Record Saved Successfully!");
message.setSeverity(FacesMessage.SEVERITY_INFO);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, message);
Code to show error msg in page
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,”msg”,null));
Code to get bindings to make custom buttons
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
OperationBinding operationBinding =bindings.getOperationBinding("Commit");
operationBinding.execute();
Code to use popup
1)showPopup method to call popup
private void showPopup(RichPopup pop, boolean visible) {
try {
FacesContext context = FacesContext.getCurrentInstance();
if (context != null && pop != null) {
String popupId = pop.getClientId(context);
if (popupId != null) {
StringBuilder script = new StringBuilder();
script.append("var popup = AdfPage.PAGE.findComponent('").append(popupId).append("'); ");
if (visible) {
script.append("if (!popup.isPopupVisible()) { ").append("popup.show();}");
} else {
script.append("if (popup.isPopupVisible()) { ").append("popup.hide();}");
}
ExtendedRenderKitService erks =
Service.getService(context.getRenderKit(), ExtendedRenderKitService.class);
erks.addScript(context, script.toString());
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
2)And import these packages
import org.apache.myfaces.trinidad.event.SelectionEvent;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;
import javax.faces.context.FacesContext;
3)To use in the page
Use binding property of Popup
private RichPopup pop;
Now use above showPopup method to show popup in any method or button action.
showPopup(pop, true);
Popup Dialog listener
Place dialog in popup and use Dialog Listner event of dialog to perform action of used button of dialog.
For ex:- we use ok button of Dialog .So to perform action of Ok button we have to bind DialogListner property of Dialog and use following code.
public void dailogok(DialogEvent dialogEvent) {
if(dialogEvent.getOutcome().name().equals("ok")){
BindingContainer bindings = getBindings();
OperationBinding operationBinding =bindings.getOperationBinding("Commit");
operationBinding.execute();
}
Code for email validation
public void emailValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
if(object!=null){
String name=object.toString();
String expression="^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
CharSequence inputStr=name;
Pattern pattern=Pattern.compile(expression);
Matcher matcher=pattern.matcher(inputStr);
String msg="Email is not in Proper Format";
if(matcher.matches()){
}
else{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null));
}
}
}
Code to validate duplicate record
public void deptNameValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
DuplicateRecordValidationAMImpl am = (DuplicateRecordValidationAMImpl)resolvElDC("DuplicateRecordValidationAMDataControl");
DepartmentViewImpl departmentView1 = am.getDepartmentView1();
Row[] filteredRowsInRange = departmentView1.getFilteredRows("DepartmentName", object.toString());
// departmentView1.getAllRowsInRange();
int i=filteredRowsInRange.length;
String msg="Department with the same name found.Please enter any other name.";
if(i>1){
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null));
}
}
Phone Number validation
public void phoneNoValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
String msg2 = "";
if (object != null) {
String phnNo = object.toString();
int openB = 0;
int closeB = 0;
boolean closeFg = false;
char[] xx = phnNo.toCharArray();
for (char c : xx) {
if (c == '(') {
openB = openB + 1;
} else if (c == ')') {
closeB = closeB + 1;
}
if (closeB > openB) {
closeFg = true; //closed brackets will not be more than open brackets at any given time.
}
}
//if openB=0 then no. of closing and opening brackets equal || opening bracket must always come before closing brackets
//closing brackets must not come before first occurrence of openning bracket
if (openB != closeB || closeFg == true || (phnNo.lastIndexOf("(") > phnNo.lastIndexOf(")")) ||
(phnNo.indexOf(")") < phnNo.indexOf("("))) {
msg2 = "Brackets not closed properly.";
FacesMessage message2 = new FacesMessage(msg2);
message2.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message2);
}
if (phnNo.contains("()")) {
msg2 = "Empty Brackets are not allowed.";
FacesMessage message2 = new FacesMessage(msg2);
message2.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message2);
}
if (phnNo.contains("(.") || phnNo.contains("(-") || phnNo.contains("-)")) {
msg2 = "Invalid Phone Number.Check content inside brackets.";
FacesMessage message2 = new FacesMessage(msg2);
message2.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message2);
}
openB = 0;
closeB = 0;
closeFg = false;
//check for valid language name.Allowed- brackets,dots,hyphen
String expression = "([0-9\\-\\+\\(\\)]+)";
CharSequence inputStr = phnNo;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
String error = "Invalid Phone Number";
if (matcher.matches()) {
if (phnNo.contains("++") || phnNo.contains("--")) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Can not contain two hyphen(--) or plus(++)"));
} else if (phnNo.lastIndexOf("+") > 1) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Plus sign should be in proper place"));
} else if (phnNo.lastIndexOf("+") == 1 && phnNo.charAt(0) != '(') {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Plus sign should be in proper place"));
}
else if(phnNo.startsWith(" ") || phnNo.endsWith(" ")){
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Space Not allowed at start and end"));
}
} else {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Only numeric character,+,() and - allowed"));
}
}
}
Using groovy expression (sample format)
Groovy expressions can be placed in a number of different places in ADF Business
Components. For the main part, you will probably be applying them in entity and view object
attribute values and for entity object validations.
Mostly we can use groovy expression for Transient object
1)When used to calculate many fields of an VO and show the sum in the same VO.
object.getRowSet().sum("Salary")
2)Sample format to use Groovy expression for transient object
CommissionPct==null? Salary:Salary+Salary*CommissionPct
(Condition) ? (When true) : (When false)
Refresh page through java code
protected void refreshPage() {
FacesContext fc = FacesContext.getCurrentInstance();
String refreshpage = fc.getViewRoot().getViewId();
ViewHandler ViewH =
fc.getApplication().getViewHandler();
UIViewRoot UIV = ViewH.createView(fc,refreshpage);
UIV.setViewId(refreshpage);
fc.setViewRoot(UIV);
}
Partially refresh on any UI Component
Here we use binding property of UI Component
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);
To implement resolvEDIC method
public Object resolvElDC(String data) {
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, "#{data." + data + ".dataProvider}", Object.class);
return valueExp.getValue(elContext);
}
Use this in code to get Application Module Impl class
AppModuleAMImpl am =
(AppModuleAMImpl)resolvElDC("AppModuleAMDataControl");
Code to show FacesMessege in page
FacesMessage message = new FacesMessage("Record Saved Successfully!");
message.setSeverity(FacesMessage.SEVERITY_INFO);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, message);
Code to show error msg in page
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,”msg”,null));
Code to get bindings to make custom buttons
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
OperationBinding operationBinding =bindings.getOperationBinding("Commit");
operationBinding.execute();
Code to use popup
1)showPopup method to call popup
private void showPopup(RichPopup pop, boolean visible) {
try {
FacesContext context = FacesContext.getCurrentInstance();
if (context != null && pop != null) {
String popupId = pop.getClientId(context);
if (popupId != null) {
StringBuilder script = new StringBuilder();
script.append("var popup = AdfPage.PAGE.findComponent('").append(popupId).append("'); ");
if (visible) {
script.append("if (!popup.isPopupVisible()) { ").append("popup.show();}");
} else {
script.append("if (popup.isPopupVisible()) { ").append("popup.hide();}");
}
ExtendedRenderKitService erks =
Service.getService(context.getRenderKit(), ExtendedRenderKitService.class);
erks.addScript(context, script.toString());
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
2)And import these packages
import org.apache.myfaces.trinidad.event.SelectionEvent;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;
import javax.faces.context.FacesContext;
3)To use in the page
Use binding property of Popup
private RichPopup pop;
Now use above showPopup method to show popup in any method or button action.
showPopup(pop, true);
Popup Dialog listener
Place dialog in popup and use Dialog Listner event of dialog to perform action of used button of dialog.
For ex:- we use ok button of Dialog .So to perform action of Ok button we have to bind DialogListner property of Dialog and use following code.
public void dailogok(DialogEvent dialogEvent) {
if(dialogEvent.getOutcome().name().equals("ok")){
BindingContainer bindings = getBindings();
OperationBinding operationBinding =bindings.getOperationBinding("Commit");
operationBinding.execute();
}
Code for email validation
public void emailValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
if(object!=null){
String name=object.toString();
String expression="^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
CharSequence inputStr=name;
Pattern pattern=Pattern.compile(expression);
Matcher matcher=pattern.matcher(inputStr);
String msg="Email is not in Proper Format";
if(matcher.matches()){
}
else{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null));
}
}
}
Code to validate duplicate record
public void deptNameValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
DuplicateRecordValidationAMImpl am = (DuplicateRecordValidationAMImpl)resolvElDC("DuplicateRecordValidationAMDataControl");
DepartmentViewImpl departmentView1 = am.getDepartmentView1();
Row[] filteredRowsInRange = departmentView1.getFilteredRows("DepartmentName", object.toString());
// departmentView1.getAllRowsInRange();
int i=filteredRowsInRange.length;
String msg="Department with the same name found.Please enter any other name.";
if(i>1){
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null));
}
}
Phone Number validation
public void phoneNoValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
String msg2 = "";
if (object != null) {
String phnNo = object.toString();
int openB = 0;
int closeB = 0;
boolean closeFg = false;
char[] xx = phnNo.toCharArray();
for (char c : xx) {
if (c == '(') {
openB = openB + 1;
} else if (c == ')') {
closeB = closeB + 1;
}
if (closeB > openB) {
closeFg = true; //closed brackets will not be more than open brackets at any given time.
}
}
//if openB=0 then no. of closing and opening brackets equal || opening bracket must always come before closing brackets
//closing brackets must not come before first occurrence of openning bracket
if (openB != closeB || closeFg == true || (phnNo.lastIndexOf("(") > phnNo.lastIndexOf(")")) ||
(phnNo.indexOf(")") < phnNo.indexOf("("))) {
msg2 = "Brackets not closed properly.";
FacesMessage message2 = new FacesMessage(msg2);
message2.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message2);
}
if (phnNo.contains("()")) {
msg2 = "Empty Brackets are not allowed.";
FacesMessage message2 = new FacesMessage(msg2);
message2.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message2);
}
if (phnNo.contains("(.") || phnNo.contains("(-") || phnNo.contains("-)")) {
msg2 = "Invalid Phone Number.Check content inside brackets.";
FacesMessage message2 = new FacesMessage(msg2);
message2.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message2);
}
openB = 0;
closeB = 0;
closeFg = false;
//check for valid language name.Allowed- brackets,dots,hyphen
String expression = "([0-9\\-\\+\\(\\)]+)";
CharSequence inputStr = phnNo;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
String error = "Invalid Phone Number";
if (matcher.matches()) {
if (phnNo.contains("++") || phnNo.contains("--")) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Can not contain two hyphen(--) or plus(++)"));
} else if (phnNo.lastIndexOf("+") > 1) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Plus sign should be in proper place"));
} else if (phnNo.lastIndexOf("+") == 1 && phnNo.charAt(0) != '(') {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Plus sign should be in proper place"));
}
else if(phnNo.startsWith(" ") || phnNo.endsWith(" ")){
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Space Not allowed at start and end"));
}
} else {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,"Only numeric character,+,() and - allowed"));
}
}
}
Using groovy expression (sample format)
Groovy expressions can be placed in a number of different places in ADF Business
Components. For the main part, you will probably be applying them in entity and view object
attribute values and for entity object validations.
Mostly we can use groovy expression for Transient object
1)When used to calculate many fields of an VO and show the sum in the same VO.
object.getRowSet().sum("Salary")
2)Sample format to use Groovy expression for transient object
CommissionPct==null? Salary:Salary+Salary*CommissionPct
(Condition) ? (When true) : (When false)
Refresh page through java code
protected void refreshPage() {
FacesContext fc = FacesContext.getCurrentInstance();
String refreshpage = fc.getViewRoot().getViewId();
ViewHandler ViewH =
fc.getApplication().getViewHandler();
UIViewRoot UIV = ViewH.createView(fc,refreshpage);
UIV.setViewId(refreshpage);
fc.setViewRoot(UIV);
}
Partially refresh on any UI Component
Here we use binding property of UI Component
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);
Tuesday, October 29, 2013
Pass additional values to Listener using SetPropertyListener
Scenario: User enters bonus amount. If Salary+Bonus is greater than 1,50,000 show alert message.
Step1:Create VO with Salary and Bonus attributes. Create a table in JSPX page.
Step2: Set Bonus input text field properties.. add validate method to ValueChangeListener and set AutoSubmit to true.
Step1:Create VO with Salary and Bonus attributes. Create a table in JSPX page.
Step2: Set Bonus input text field properties.. add validate method to ValueChangeListener and set AutoSubmit to true.
Step3: Add setPropertyListener on Bonus inputtext field.
From: Source value(Value to be saved in scope for later use) Ex: #{row.bindings.Salary.inputValue}
To: Variable Name(Scope and Variable to hold the source value) Ex; #{pageFlowScope.CurrRowSalaryVar}
Type: Listener Type Ex: valueChange
Step4: Add code in bean.
public void validateTotalSalary(ValueChangeEvent ve){
BigDecimal bonus = (BigDecimal)ve.getNewValue();
BigDecimal salary = (BigDecimal)AdfFacesContext.getCurrentInstance().getPageFlowScope().get("CurrRowSalaryVar");
int ibonus = bonus.intValue();
int isalary= salary.intValue();
if(bonus!=null && salary!=null && (ibonus+isalary)>150000){
FacesMessage msg = new FacesMessage("Total Salary exceeded 1,50,000.");
msg.setSeverity(FacesMessage.SEVERITY_INFO);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, msg);
}
}
Step5: Ouput
PPR on Table Row
Scenario: On Update in Bonus field of selected row, TotalSalary should get updated by Salary+Bonus amounts.
Step1: Create VO. Add TotalSalary as Transient attribute. Create table in JSP page.
Step2: Add ValueChangeListner on Bonus InputText box. Set AutoSubmit to true.
Step1: Create VO. Add TotalSalary as Transient attribute. Create table in JSP page.
Step2: Add ValueChangeListner on Bonus InputText box. Set AutoSubmit to true.
Step3:Create method in bean.
public void setTotalAmt(ValueChangeEvent ve){
//BigDecimal bonus = (BigDecimal)ve.getNewValue();
for (Object facesRowKey : t1.getSelectedRowKeys()) {
t1.setRowKey(facesRowKey);
Object o = t1.getRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
BigDecimal salary = (BigDecimal)row.getAttribute("Salary");
BigDecimal bonus = (BigDecimal)row.getAttribute("Bonus");
row.setAttribute("TotalSalary", salary.add(bonus));
}
}
Monday, October 28, 2013
ADF Security
1.Print the roles of the current user
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
System.out.println("role "+role);
}
2.Get the ADF security context and test if the user has the role users
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole("users") ) {
}
3.Is the user valid
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();}
4.Return the user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();
}
Source: http://blog.whitehorses.nl/2010/02/01/weblogic-web-application-container-security-part-2-adf-security/
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
System.out.println("role "+role);
}
2.Get the ADF security context and test if the user has the role users
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole("users") ) {
}
3.Is the user valid
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();}
4.Return the user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();
}
Source: http://blog.whitehorses.nl/2010/02/01/weblogic-web-application-container-security-part-2-adf-security/
Friday, October 25, 2013
Accessing URL Params
1. Using Groovy:
URL: http://highbrow:7101/TestUrl/Faces/TestPage.jspx?pupOrderNumber=27826728&pageMode=PUP
#{param.pupOrderNumber} -- returns its value: 27826728
#{param.pageMode} -- returns its value: PUP
2. Programmatically:
HttpServletRequest request =(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String ordNum = request.getParameter("pupOrderNumber");
String pMode= request.getParameter("pageMode");
or
FacesContext fctx = FacesContext.getCurrentInstance();
ExternalContext ectx = fctx.getExternalContext();
java.util.Map params = ectx.getRequestParameterMap();
String ordNum = (String)params.get("pupOrderNumber");
String pMode = (String)params.get("pageMode");
URL: http://highbrow:7101/TestUrl/Faces/TestPage.jspx?pupOrderNumber=27826728&pageMode=PUP
#{param.pupOrderNumber} -- returns its value: 27826728
#{param.pageMode} -- returns its value: PUP
2. Programmatically:
HttpServletRequest request =(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String ordNum = request.getParameter("pupOrderNumber");
String pMode= request.getParameter("pageMode");
or
FacesContext fctx = FacesContext.getCurrentInstance();
ExternalContext ectx = fctx.getExternalContext();
java.util.Map params = ectx.getRequestParameterMap();
String ordNum = (String)params.get("pupOrderNumber");
String pMode = (String)params.get("pageMode");
Tuesday, October 22, 2013
Accesing Login User Details
1- Using Groovy: We can set default expression in view object attribute as below
adf.context.securityContext.getUserPrincipal().getName()
or
adf.context.securityContext.getUserName()
2- Java Code: You can get User Name in Java code also using the following code.
ADFContext adfCtx = ADFContext.getCurrent();
SecurityContext secCntx = adfCtx.getSecurityContext();
String user = secCntx.getUserPrincipal().getName();
String _user = secCntx.getUserName();
3-Expression Language: You can bind ADF Faces componenets with the following EL to get logged User Name.
#{securityContext.userName}
Source:http://mahmoudoracle.blogspot.in/2012/06/adf-get-current-logged-user-name.html#.UmTBMPlHK8w
adf.context.securityContext.getUserPrincipal().getName()
or
adf.context.securityContext.getUserName()
2- Java Code: You can get User Name in Java code also using the following code.
ADFContext adfCtx = ADFContext.getCurrent();
SecurityContext secCntx = adfCtx.getSecurityContext();
String user = secCntx.getUserPrincipal().getName();
String _user = secCntx.getUserName();
3-Expression Language: You can bind ADF Faces componenets with the following EL to get logged User Name.
#{securityContext.userName}
Source:http://mahmoudoracle.blogspot.in/2012/06/adf-get-current-logged-user-name.html#.UmTBMPlHK8w
Monday, October 14, 2013
Attributes of the PageDef.xml File Element
Tip:
You can determine the order of executable invocation using the refreshAfter
attribute. For example, say you have two invokeAction
elements; one with an ID of myAction
and another with an ID of anotherAction
, and you want myAction
to fire afteranotherAction
. You would set the refreshAfter
condition on myAction
toanotherAction
.Execute some code when the page loads in adf
There are many ways to execute some code before loading the page in adf.
They are:
1. By using Method activity in the Task flow.
We can achieve this in 2 ways again.
a. Add the code to be executed, to a method in ApplicationModuleImpl class and expose it to client interface. From Data Control panel drag and drop that method to the Task flow. In the task flow add the page (view activity) and navigation from the method activity to the view acitvity. In this approach, first the method will be invoked before rendering the page.
b. Add the code to be executed to the managed bean and add a method call activity to the Task flow. For that method call activity bind the method in the Managed bean. Now add the view activity(page) and add navigation from method call activity to the view activity. In this approach, first the method from the managed bean will be invoked before rendering the page.
2. Using invokeAction executables.
This approach is used when we dont want to use taskflow method call to execute this page load code. If we dont have any task flows in our application and we are using only jsf pages, then this is the best approach. Add the code to the method in the ApplicationModuleImpl class and expose it to the client interface. Go to the pagedef file corresponding to the page and in the bindings section add the method from datacontrol. Now in the executables section add invokeAction executable. It will ask for some id and in the binds field specify the method action added in the bindings. Select the executabel now and go to Property Inspector. In the Refresh property specify “renderModel”. Now it will be executed before the page loads.
3. Using Server and ClientListener code
In the jspx page give the code in the following manner.
af:document id=”d1″
af:serverListener type=”onloadEvent”
method=”#{managedbean name.method name}”
af:clientListener method=”onLoadClient” type=”load”
af:resource type=”javascript”
function onLoadClient(event) {
AdfCustomEvent.queue(event.getSource(),”onloadEvent”,{},false);
return true;
}
af:resource
Source: http://adfnbpel.wordpress.com/2012/08/07/execute-some-code-when-the-page-loads-in-adf/
They are:
1. By using Method activity in the Task flow.
We can achieve this in 2 ways again.
a. Add the code to be executed, to a method in ApplicationModuleImpl class and expose it to client interface. From Data Control panel drag and drop that method to the Task flow. In the task flow add the page (view activity) and navigation from the method activity to the view acitvity. In this approach, first the method will be invoked before rendering the page.
b. Add the code to be executed to the managed bean and add a method call activity to the Task flow. For that method call activity bind the method in the Managed bean. Now add the view activity(page) and add navigation from method call activity to the view activity. In this approach, first the method from the managed bean will be invoked before rendering the page.
2. Using invokeAction executables.
This approach is used when we dont want to use taskflow method call to execute this page load code. If we dont have any task flows in our application and we are using only jsf pages, then this is the best approach. Add the code to the method in the ApplicationModuleImpl class and expose it to the client interface. Go to the pagedef file corresponding to the page and in the bindings section add the method from datacontrol. Now in the executables section add invokeAction executable. It will ask for some id and in the binds field specify the method action added in the bindings. Select the executabel now and go to Property Inspector. In the Refresh property specify “renderModel”. Now it will be executed before the page loads.
3. Using Server and ClientListener code
In the jspx page give the code in the following manner.
af:document id=”d1″
af:serverListener type=”onloadEvent”
method=”#{managedbean name.method name}”
af:clientListener method=”onLoadClient” type=”load”
af:resource type=”javascript”
function onLoadClient(event) {
AdfCustomEvent.queue(event.getSource(),”onloadEvent”,{},false);
return true;
}
af:resource
Source: http://adfnbpel.wordpress.com/2012/08/07/execute-some-code-when-the-page-loads-in-adf/
Page Definition Variables
We can use Page Definition variables to store temporary values, these values will be preserved between requests.
Details: http://andrejusb.blogspot.in/2011/10/page-definition-variables-to-store.html
Details: http://andrejusb.blogspot.in/2011/10/page-definition-variables-to-store.html
Friday, September 20, 2013
SOA Interview Questions
1) What is SOA?
Service Oriented
Architecture (SOA) is used to develop Enterprise applications by using a
collection of services which communicates each other. Service-Oriented
Architecture (SOA) is a set of principles and methodologies for designing and
developing software in the form of interoperable services.
2) Principles of SOA?
· loose
coupling
· Re-usability
· Interoperability
· Flexible
3) What is the difference between 10g
and 11g?
SCA architecture was
followed in 11g and not in 10g
· In
11g you can put all your project SOA components in composite.xml file and
deploy as a single deployment unit to single server, where in 10g you have to
deploy each component to the
respective server (i.e. ESB to ESB server, BPEL to BPEL Server)
· Basically
all the SOA components like BPEL, ESB (Called Mediator in 11g), & OWSM
are brought into one place in 11g using SCA composite concept.
· The
major difference between 10g & 11g would be the app server container.
10g by default runs onOC4J while 11g runs on Web logic Server.
· In
10g every BPEL is a separate project, but in 11g several components can make 1
project as SCA.
· In
10g consoles are separate for BPEL and ESB, but in 11g Enterprise Manager
contains all.
· In
10g BAM and business rules are outside SOA Suite, but in 11g they are in SOA
Suite.
4) Is Oracle SOA same as Oracle
Fusion Middleware?
No because SOA is one of
the parts in Fusion middleware and
SOA behaves like user interface where as Fusion is big platform
SOA behaves like user interface where as Fusion is big platform
5) What is SCA?
Service Component
Architecture (SCA) provides a programming model for building applications and
systems based on a Service Oriented Architecture. SCA is a model that aims to
encompass a wide range of technologies for service components and for the
access methods which are used to connect them.
6) What is the SOA Suite 11g
Components?
· Oracle
Adapters
· Oracle
Mediator
· Business
Events and Events Delivery Network
· Oracle
Business Rules
· Human
Workflow
· Oracle
Business Activity Monitoring
· Oracle
Enterprise Manager
7) What is choreography? How does it differ
from orchestration?
In choreography there is
no business process to control the integration between the systems; each system
will directly integrate with one another in sequence where as in Orchestration
there is a business process which controls all the services (source/Target)
which is part of the integration.
8) What are the different design patterns
in SOA?
· Synchronous
· Asynchronous
Fire and Forget
· Asynchronous
Delayed Response.
9) In how many ways can a process be
deployed?
· Using
JDeveloper
· Through
Enterprise Manger Console
· Through
Weblogic Scripts.
10) What are dspMaxThread and a recieverThread properties?
Why are they important?
ReceiverThreads property
specifies the maximum number of MDBs that process aysc across all domains.
Whereas the dspMaxThreads are the maximum number of MDBs that process asy and
threads that operate across a domain.
So, we need to ensure
that the dspMaxThreads value is !> ReceiverThreads.
11) How does a async request run in the backend?
The sequence of events
involved in the delivery of invoke messages is as follows:
· The
client posts the message to the delivery service.
· The
delivery service saves the invocation message to the invoke_message table.The
initial state of the message is 0
(undelivered).
· The
delivery service schedules a dispatcher message to process the invocation
message asynchronously.
· The
dispatcher message is delivered to the dispatcher through the afterCompletion()
call. Therefore, the message is not delivered if the JTA transaction fails.
· The
dispatcher sends the JMS message to the queue. Places a very short JMS message
in the in-memory queue(jms/collaxa/BPELWorkerQueue) in OC4J JMS. The small JMS
message triggers the WorkerBean in the downstream step.
· This
message is then picked up by a WorkerBean MDB, which requests the dispatcher
for work to execute. If the number of WorkerBean MDBs currently processing
activities for the domain is sufficient, the dispatcher module may decide not
to request another MDB.
· MDB
fetches the invocation message from the dispatcher.
· MDB
passes the invocation message to Oracle BPEL Server, which updates the
invocation message state to 1 (delivered), creates the instance, and executes
the activities in the flow until a breakpoint activity is reached.
12) How to increase the transaction timeouts in SOA?
For the transaction
timeout needs to be increased, all the below settings timeout value needs to be
changed to the expected Timeout value.
· JTA
· Engine
Bean
· Delivery
Bean
13) Is it possible to use MS SQL Server as dehydration store
with SOA Suite ?if yes how?
Yes it is possible.
To automatically
maintain long-running asynchronous processes and their current state
information in a database while they wait for asynchronous callbacks, you use a
database as a dehydration store.Storing the process in a database preserves the
process and prevents any loss of state or reliability if a system shuts down or
a network problem occurs. This feature increases both BPEL process reliability
and scalability. You can also use it to support clustering and failover.
14) What is SOA governance? What are its functions?
Service-Oriented
Architecture (SOA) governance is a concept used for activities related to
exercising control over services in an SOA Some key activities that are often
mentioned as being part of SOA governance are:
Managing the portfolio
of services: This includes planning development of new services and updating
current services.Managing the service lifecycle: This is meant to ensure that
updates of services do not disturb current services to the consumers. Using
policies to restrict behavior: Consistency of services can be ensured by having
the rules applied to all the created services. Monitoring performance of
services: The consequences of service downtime or underperformance can be
severe because of service composition. Therefore action can be taken instantly
when a problem occurs by monitoring service performance and availability.
15) What is end point virtualization?
Generally a service bus
is used for endpoint virtualization and in 11g stack; Oracle Service Bus (OSB)
is the primary service bus. In exposed proxy's message flow, it can route the
request to any of your environment's actual (physical) service on the basis of
whatever logic.
Mediator can also be used to expose the service and in mediator routing rule, it can be routed to actual service.
Mediator can also be used to expose the service and in mediator routing rule, it can be routed to actual service.
16) What are DVM's and how are they helpful in SOA?
DVM-Domain Value
Map are static mappings between a source and target system which can be
used in transformations. The value can be changed via SOA composer.
17) What is the difference between XREF and DVM?
XREF- It is dynamic
since the values to the XREF can be populated dynamically and it is stored in
XREF_DATA table in SOA Dehydration store.
DVM- Domain Value
Map is static mappings between a source and target system which can be
used in transformations.
18) What is Dehydration store?
Dehydration store is the
database where the instances get stored when it gets dehydrated by the process
on the occurrence of non-idempotent activities and also stores the information
on the long running processes.
19) What is Decision service?
Oracle SOA Suite
provides support for Decision components that support Oracle Business Rules. A
Decision component is a mechanism for publishing rules and rulesets as a
reusable service that can be invoked from multiple business processes.These
rules can be changed without redeploying the code.
20) Why we use BPEL and OSB?
OSB is the light-weight
service bus wherever there is not much business logic involves and there is
need to just get the message routed between the systems OSB is used where as
when there is more business logic involves in the process,then BPEL will be used.
21) What is MDS?
MDS –Metadata Store
Wsdl and Schemas to be
used in the process can be published to the MDS and get it used in the code by
referring the artifacts from the MDS
Advantages:
- JAR (Deployment unit) size will be reduced.
- Duplication of the artifacts can be avoided between the services.
22) What is a XA datasource? How it differs from a non-XA
datasource?
An XA transaction
involves a coordinating transaction manager, with one or more databases
(or other resources, like JMS) all involved in a single global transaction.
Non-XA transactions have no transaction coordinator, and a single resource is
doing all its transaction work itself (this is sometimes called local
transactions).
23) How can we secure our web services using Oracle SOA
Suite?
When accessing the
services should be restricted to the group,then service should be secured via
WSM (Web service Manager).
24) How to deploy an XSL file without deployment of BPEL
Process?
We will directly deploy
the XSLT, options: -
- Using ANT script by file replacement in TMP folder.
- By creating a folder in BPEL PM installation folder and specifying its location in our BPEL code with http call and replacing our xslt to that location.
25) What is HA File and FTP Adapters?
In the clustered
environment,File and FTP adapters should be used as HA(High-Availability)
Inbound:It is
controlled by Control Files and avoids the race between the manages servers in
reading the files where the reference of the files read by the managed servers
will be maintained in the control directory.
Outbound:It is
controlled by DB Mutex table exist in the SOA dehydration store and this
avoids duplicated been written to the same file when all the managed servers in
the clusters process the same messages.
26) What is singleton Property in SOA?
In the clustered
environment when the processing of the message should happen via only one SOA
managed server, then the property singleton needs to be defined at the adapter
level.
27) What is a pick activity? Can I have a pick activity with
no onMessage branch?
Pick activity picks the
messages from service (Source) which has multiple operations or the BPEL
process needs to receive the messages from multiple source system. Pick
activity should have at least on Message branch.
28) What is a flow activity? What is a flowN activity and how
does it leverages the flow activity?
Flow activity is used,
when parallel execution of the flow is needed and to use this property “non
blocking invoke should be set as true “at the partner link level and no. of
execution of parallel flow is defined and static. Where as in Flown the no. of
execution of parallel flow is not static and it is determined during run time.
29) What do you mean by non-idempotent activity? Which
all activities are non-idempotent by default?
Activities like Pick,
Wait, receive, reply and checkpoint() are called non-Idempotent activity and
during the execution of the process whenever these activities are encountered
then it gets dehydrated to the dehydration store.
30) How can we embed or use a java code in BPEL?
Using JAVA embedding
activity in BPEL,Java code can be embedded in BPEL and can be used.
31) How does pick activity differ from a receive activity?
Pick activity can act as
a multiple recieve activity in some business scenarios.If we have two inbound
operations and both can trigger the bpel process then we will go with pick
activity as we can’t have two recieve activity with create Instance box
checked.
32) How can we make a partner link dynamic?
If we have to send the
request to different service which has the same wsdl then dynamic partner link
will be used and using addressing schema we can set the endpoint dynamic to
send the request to the desired service.
33) What is a nonBlockingAll property?
Non- blocking invoke is
used when Parallel flow needs to be executed where new thread will be created
for each invoke a activity and which will execute simultaneously.
34) What is getPreference property? How do we set it and what
advantage it provides?
Hard coding is not a
good practice, so to avoid hard coding preference variable can be used
and the value of the preference variable is accessed using getPreference().The
preference variable value can be changed without re-deploying the code via em
console MBean property.
35) How can we improve the performance of an XSL file?
By avoiding use of
various if statements and using choose, and by using for-each group in place of
for-each.
36) How do we handle transactions in BPEL?
Property needs to be defined
to start the new transaction/to continue with the same transactions
Property Name:
Transaction and if this has value as required then the BPEL process will be
continued in the same transaction where as if the value is defined as
requiresnew then it will start the new transaction.
37) What are transient and durable BPEL processes?
Durable:-It is long
running process and initiated through a one-way invocation and do incur
one or more dehydration points in the database during execution Ex:
Asynchronous
Transient:-It is
short-lived process, request-response style processes and do not incur
dehydration during their process execution Ex: Synchronous.
38) When u will go for Sync process?
Whenever the services
returns the response in few seconds, it is recommended to go for synchronous
BPEL process if not the BPEL process should be Asynchronous the reason is
calling application can’t proceed further in case of synchronous process.
39) What is a syncFileRead operation? Is a inbound or a
outbound operation? Can my process begin with syncFileRead operation?
When file has to be read
in the mid of the BPEL process, then we will use syncFileRead Operation, means
some process should initiate the file read process and it is an outbound
operation and process can’t begin with Sync File read.
40) Can we use a File Adapter to get a file without reading
its content?
Yes, by selecting
the Do not read file content check box in the JDeveloper wizard while
configuring the "Read operation."
41) How to increase performance increase in bpel (Db
Adapter/file adapter)?
We can increase the
performance by writing indexes and sequences.
(Or) Go to application
server --- >Configurations ----- > Change Xml file
42) Explain error handling in BPEL and what is a error
handling framework? How does a error handling framework better than
simple error handling in BPEL?
EHF –Whenever any error
thrown by the BPEL process/Mediator then EHF will check whether exist in
Fault-Bindings.xml files and if so then the action in
the Fault-Policy.xml file will be taken and if the action is not found then the
fault will the thrown and it will be handled in the catch block.
43) How do we resubmit a faulted process?
Scenario A: The BPEL
code uses a fault-policy and a fault is handled using the
“ora-human-intervention” activity, then the fault is marked as Recoverable and
the instance state is set to “Running”.
Scenario B: The BPEL
code uses a fault-policy and a fault is caught and re-thrown using the
“ora-rethrow-fault” action, then the fault is marked as Recoverable and the
instance state is set to “Faulted”; provided the fault is a recoverable one
(like URL was not available).
44) Predefined errors in BPEL?
- Custom errors
- Timed out errors
- BPM errors
- Validation Errors
45) What is a throw activity? What it is ?
Throw activity will
explicitly throw the fault and this fault will get caught by the catch block
and the corresponding actions will get executed.
46) What is Web service?
Web services are
application components, which are self-contained and self-describing and
provide services based on the open protocol communication (i.e. SOAP UI, HTTP
over the net).
47) Difference between URI and URL?
A URI is an identifier
for some resource, but a URL gives you specific information as to obtain that
resource. A URI is a URL and as one commenter pointed out, it is now considered
incorrect to use URL when describing applications. Generally, if the URL
describes both the location and name of a resource, the term to use is URI.
Since this is generally the case most of us encounter every day, URI is the
correct term.
48) What is Mediator?
The Mediator is in
charge of interconnecting, within an SOA composite application, components that
expose different interfaces. In addition, the Mediator can perform duties such
as filtering and making routing decisions.
The composite editor in
JDeveloper gives you the flexibility to define the interface now, to choose an
existing interface, or to define the interface later as you wire components to
the Mediator.
Transforming data from
one representation to another is, along with routing, one of the key functions
of the Mediator.
49) Difference between ESB and Mediator?
In 10g for routing, separate router need to keep along with ESB for routing and filter expressions.
Where as in 11g mediator contains routing rules and filter expressions itself.
50) What is the difference between concrete and abstract
wsdl?
Concrete: Besides the
information about how to communicate to the web service, it the information on
where the service exist. It has Bindings (Protocol the message should be sent)
and Services(has endpoint for each bindings) .
Abstract: It has
information about how to communicate to the web service like types (Schema),
Message (input and output messages service accepts) ,Operations (operation that
can be performed on this service) and port Type.
51) What is SOAP and what are the binding protocols
available?
Simple object access
protocol and it is a protocol specification for the communication happens
between the web services over the network and binding protocol is HTTP.
52) What is the difference between Async and Sync activity on
wsdl level?
- Async wsdl-It has only input messages for the operation and it has 2 operations one for sending the request and other for call back.
- Sync wsdl-It has 2 messages input and output messages for the wsdl operation.
53) What are the WSDL structure?
Following are the wsdl
structure
- definitions
- Types
- Messages
- Operation
- Port type
- Bindings
- Services
- Ports
54) What is the significance of target Namespace in a wsdl?
It is the one which
uniquely identifies the WSDL and when the WSDL is used it should be identified
using its Target Namespace.
55) What is structure of SOAP message?
The structure of a SOAP
message: A SOAP message is encoded as an XML document, consisting of an
element, which contains an optional element, and a mandatory element. The
element, contained within the , is used for reporting errors.
The SOAP envelope-The SOAP
is the root element in every SOAP message, and contains two child elements, an
optional and a mandatory.
The SOAP header-The SOAP
is an optional sub-element of the SOAP envelope, and is used to pass
application-related information that is to be processed by SOAP nodes along the
message path.
The SOAP body-The SOAP
is a mandatory sub-element of the SOAP envelope, which contains information
intended for the ultimate recipient of the message.
The SOAP fault-The SOAP
is a sub-element of the SOAP body, which is used for reporting errors.
56) Why do we need to have messages in WSDL, aren't
operations and types enough to describe the parameters for a web service?
Messages consist of one
or more logical parts. Each part is associated with a type from some type
system using a message-typing attribute. The set of message-typing attributes
is extensible.
- The element describes the data being exchanged between the Web service providers and consumers. Each Web Service has two messages: input and output.
- The input describes the parameters for the Web Service and the output describes the return data from the Web Service.
- Each message contains zero or more parameters, one for each parameter of the Web Service's function.
- Each parameter associates with a concrete type defined in the container element. So describing the parameters cannot performed by operations and types this is the main need of Messages.
57) What is a inline schema?
Schemas can be included
inside of XML file is called Inline Schemas.
58) What is the difference between xsd:import and
xsd:include?
The fundamental
difference between include and import is that you must use import to refer to
declarations or definitions that are in a different target namespace and you
must use include to refer to declarations or definitions that are (or will be)
in the same target namespace.
59) What is BAM?
Business Activity
Monitoring is a tool that is useful in monitoring business services and
processes. It actively collects data, applies rules and reports information to
users. When something goes wrong in business processes, BAM can be configured
to take corrective measures such as emailing administrators/support team.
60) How to send the data to BAM from SOA?
The Oracle BAM Adapter
is a Java Connector Architecture (JCA)-compliant adapter which can be used from
a Java EE client to send data and events to the Oracle BAM Server. Oracle BAM
Adapter is configured in Oracle Weblogic Server Administration Console to
provide any of these connection pools. Oracle BAM Adapter provides three
mechanisms by which you can send data to Oracle BAM Active Data Cache from an
SOA composite application.
61) What are the ways to publish the data to BAM?
There are two ways to
publish the data to BAM
- BAM Adapter.
- BAM Sensor activity level.
62) What are the roles in BAM?
- Architect
- Administrator
- Active Viewer
- Active Studio
63) What is forward delay in JMS Queue?
In the clustered
environment where JMS queues are used, when for the queues in any one of the
Managed server doesn’t have the consumer, once messages reaches the
forward delay time it gets moved to the other managed server where
consumer is present.
64) What is redelivery limit in JMS Queue?
When the message gets
failed to get processed ,then it will be re-tried will the redelivery limit
exhausts and once after the redelivery limit the message can b e either moved
to the error Queue are it can be discarded.
65) What is timetodeliver in JMS Queue?
When Messages enqueued
to the JMS queue, it will be immediately consumed by the JMS Subscribers, if
any delay needs to be induced for the message consuming by the Subscribers then
timetodelivery needs to set. The JMS message will not be subscribed until
timetodelivery exhausts.
66) Difference between JMS Queues and Topics?
Queue-Message will be
subscribed by one subscriber.
Topic-Message will be
subscribed by more than one subscriber.
Subscribe to:
Posts (Atom)