Wednesday, May 25, 2016

Why non static cannot be accessed in Static context

Static variable in Java belongs to Class and its value remains same for all instance. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance(). So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.


Read more: http://javarevisited.blogspot.com/2012/02/why-non-static-variable-cannot-be.html#ixzz49gPnE7UI

Program to Calculate and Display Area of a Circle


In order to take input I have used the Scanner class, even though you can use other ways like using a Reader or InputStream, but Scanner provides lots of utility method to read any kind of data e.g. int, float, String etc, it's preferred class to read input from the console.


import java.util.Scanner;

public class CircleArea {

public static void main(String[] args) {
// TODO Auto-generated method stub

int r;
double pi =3.14;
double area;
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius of circle: ");
r = sc.nextInt();
area = pi*r*r;
System.out.println("Area of Circle :"+area);
}
}

If you want to read String, you can use nextLine(), if you want to read integer numbers, you can use nextInt(). Subsequently you can use nextFloat() to read float input, nextDouble() to read double input etc. Scanner class also allows you to define your own pattern and scan for that.
Scanner is created by passing System.in  which is a InputStream as source which means it will scan input console for data.

public class UserInputExample {

    public static void main(String args[]) {
  
        //Creating Scanner instance to scan console for User input
        Scanner console = new Scanner(System.in);
    
        System.out.println("System is ready to accept input, please enter name : ");
        String name = console.nextLine();
        System.out.println("Hi " + name + ", Can you enter an int number now?");
        int number = console.nextInt();
        System.out.println("You have entered : " + number);
        System.out.println("Thank you");
      
    }   
  
}

Wednesday, May 18, 2016

calling clientListener(JS) from ActionListener

There is no way to make it work this way, since clientListener will work BEFORE by design. However, you can achieve your goal just by launching your javascript request from actionListener directly. Do something like this in the actionListeners method:

FacesContext fctx = FacesContext.getCurrentInstance();
ExtendedRenderKitService service = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
service.addScript(fctx,"showMyTable();");

Invoke button’s action programatically in JSF using Java


Sometimes developers may want to invoke button’s action programatically without needing a user to click a button, a common use case for this scenario is implementing navigation propgramatically using Java, in this case the developer may drag and drop a button in the page and binds its action property to some static action outcome or to a method that returns a String, and set Visible property for the button to false. At some point the developer can invoke this button’s action by using this code.
FacesContext facesContext = FacesContext.getCurrentInstance();
UIViewRoot root = facesContext.getViewRoot();
//cb1 is the fully qualified name of the button
RichCommandButton button = (RichCommandButton) root.findComponent(“cb1”);
ActionEvent actionEvent = new ActionEvent(button);
actionEvent.queue();

Monday, May 16, 2016

Create a Backing Bean for Existing Page

Create a Backing Bean for Existing Page

A backing bean is a special case of managed bean that has a one-to-one relationship to a single JSF page, and it exposes setter and getter methods for the components contained on the page. In Jdeveloper you can automatically expose UI components in a new bean when you create a new page by setting the Automatically Expose New UI Components in a New Managed Bean option as shown in the figure below.
Automatically Expose New UI Components in a New Managed Bean option
But imagine you forget to set this option and later you decided to create a Backing Bean, do you need to explicitly bind each component to the backing bean?
Fortunately, you don’t need to bind the components manually, all you need is to open the page in the visual editor and  choose Design | Page Properties from the Jdeveloper menu bar as shown in the figure below:

Click on the page properties and then select the Component Binding tab from the page properties window, set the Auto Bind option, and create or select an existing managed bean.
expose3

Friday, May 6, 2016

convert af:inputText to upperCase,lowerCase,capitalize


Sometimes you need to force the user to enter upperCase or lowerCase or capitalize letters for input text component.
fortunately, there is an easy way to do this by setting contentStyle of the input text.

To enforce the user to enter upperCase text use this style:
<af:inputText label="Label 1" id="it1" contentStyle="text-transform:uppercase;"/>

To enforce the user to enter lowerCase text use this style:
<af:inputText label="Label 1" id="it1" contentStyle="text-transform:lowerCase;"/>

To enforce the user to enter capitalize text use this style:
<af:inputText label="Label 1" id="it1" contentStyle="text-transform:capitalize;"/>

Thursday, May 5, 2016

Disabling the browser form auto-complete

Disabling the browser form auto-complete

As often, somebody's heaven is another one's hell. The browser auto-complete functionality is one example for this. In Oracle ADF Faces, there is no property that switches auto complete-off for input field components or the af:formcomponent. Thanks to the ADF Faces client side architecture switching off this browser functionality is easy to achieve:
<af:form> 
  
  <af:clientListener  type="mouseOver"
                      method="suppressAutoComplete"/>
</af:form>
The mouse over event is issued one time when you enter a form. Given that you can only have a single form on a page, this means it fires one time for the page.
The JavaScript function referenced by the af:clientListener element is shown below
function suppressAutoComplete(evt){
 var domElement =
     AdfRichUIPeer.getDomContentElementForComponent(evt.getSource());
 domElement.setAttribute("autocomplete", "off" ); 
}
If you put this into a JS library that you reference from the af:resource tag then all you need to remember is add the af:clientListener tag to the af:form tag.

button enable usaing JS from Jsff page

function buttonEnableNew(event){
  var sourceComponent=event.getSource();
  var idMap=sourceComponent.getProperty('idMap');
  if(!idMap){
    return;
  }
      var idMapping=idMap.split('~');
      var componentId=null;
      var componentValidRule=null;
      var enable=true;
      for(var i=0;idMapping.length>i;i++){
          var values=idMapping[i].split('#');
          componentId=values[0];
          componentValidRule=values[1];
          if(i==idMapping.length-2 || i==idMapping.length-1){
              continue;
          }
            var inputComponent=sourceComponent.findComponent(componentId);
            if(!inputComponent){
                return;
              }
            var inputComp = AdfDhtmlEditableValuePeer.GetContentNode(inputComponent);
            var input=inputComp.value;
          if(componentValidRule=='LENGTH'){//For checking entered text not blank
            if(input.length==0){
                enable=false;
                break;
            }
          }else{//For checking reg exp
              var regExp=new RegExp(componentValidRule);
              var flag=regExp.test(input);
              if(!flag){
                enable=false;
                break;
              }
          }
      }
      var enabledBtnId=idMapping[idMapping.length-2].split('#')[0];
      var disabledBtnId=idMapping[idMapping.length-1].split('#')[0];
      if(!enabledBtnId || !disabledBtnId){
        return;
      }
      var enabledBtn=sourceComponent.findComponent(enabledBtnId);
      var disabledBtn=sourceComponent.findComponent(disabledBtnId);
      if(!enabledBtn || !disabledBtn){
        return;
      }
      if(enable){
          enabledBtn.setProperty('visible', true);
          disabledBtn.setProperty('visible', false);
          event.getSource().focus();
      }else{
          enabledBtn.setProperty('visible', false);
          disabledBtn.setProperty('visible', true);
          event.getSource().focus();             
      }
}
------------------------------------------------------------------------------------------------
 <af:inputText id="it3" label="#{null}"
                                  value="#{pageFlowScope.userVolteActivationBean.jioNumber}"
                                  simple="true"
                                  placeholder="#{viewcontrollerBundle.JIO_NUMBER}"
                                  contentStyle="width:99%!important;"
                                  styleClass="userVolteInputText"
                                  clientComponent="true"
                                  partialTriggers="cb6"
                                  maximumLength="10" autoSubmit="true"
                                  binding="#{pageFlowScope.userVolteActivationBean.inputJioNumber}">
                        <af:clientListener method="buttonEnableNew"
                                           type="keyUp"/>
                        <af:clientAttribute name="idMap"
                                            value="it3#^[0-9]{10}$~cb6#LENGTH~cb4#LENGTH"/>
  </af:inputText>
----------------------------------------------
 <af:commandButton text="#{viewcontrollerBundle.GET_OTP}"
                                      id="cb6" partialTriggers="it3"
                                      actionListener="#{pageFlowScope.userVolteActivationBean.onGetOTP}"
                                      binding="#{pageFlowScope.userVolteActivationBean.otpBtnActual}"
                                      styleClass="saveButton"
                                      partialSubmit="true"
                                      clientComponent="true" visible="false"
                                      inlineStyle="float: none;"/>

Tuesday, May 3, 2016

How to show af:message programatically

ADF Faces uses the standard JSF messaging API. JSF supports a built-in framework for messaging by allowing FacesMessage instances to be added to theFacesContext object using the addMessage(java.lang.String clientId, FacesMessage message) method. In general there are two types of messages that can be created:component-level messages, which are associated with a specific component based on any client ID that was passed to the addMessage method, and global-level messages, which are not associated with a component because no client ID was passed to the addMessage method.
in this post, I will show how to show af:message programatically.
  • global level message:
To show a global level message, use this method:
public String showMessage() {
        String messageText=”A prgramatic af:message”;
        FacesMessage fm = new FacesMessage(messageText);
        /**
         * set the type of the message.
         * Valid types: error, fatal,info,warning
         */
        fm.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, fm);
        return null;
    }
the code above will show the message in pop-up dialog as shown below.
pop-up global message
However, you can show the global message inline with the page, what you want to do is to change the inline attribute of the af:messages in your page, this component is created automatically for you when you create a page. The inline attribute controls whether to render the message list inline with the page or in a popup window, the default value is false. Normally the messages are rendered in a pop up. If this attribute is set to true, the messages list will be rendered inline with the page. To find the af:messages, open your page in the main window, from the structure window you can find it under f:view,af:document nodes. Your global message will be shown inline with page as shown below.

global message - inline with the page

  • component-level message:
To show a message inline with a component (i.e. associated with a specific UI component) you need to expose the UI component in the managed bean using theBinding property, then you can use this method:
public String showMessage() {
        String messageText=”A prgramatic af:message”;
        FacesMessage fm = new FacesMessage(messageText);
        /**
         * set the type of the message.
         * Valid types: error, fatal,info,warning
         */
        fm.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext context = FacesContext.getCurrentInstance();
        //departmentName is the binding property for our field.
        context.addMessage(getDepartmentName().getClientId(context), fm);
        return null;
    }
The code above will show the message associated with department name field as shown below:
component-level messages

Monday, May 2, 2016

Validator Tags

1
1Create a validator class by implementing javax.faces.validator.Validatorinterface.
2Implement validate() method of above interface.
Validates length of a string

2
Validates range of numeric value
3
Validates range of float value
<f:validateDoubleRange minimum="1000.50" maximum="10000.50" />
4
Validate JSF component with a given regular expression.
<f:validateRegex pattern="((?=.*[a-z]).{6,})" />
5
Creating a custom validator