Friday, March 9, 2018

How to Set Path for Java In Mac

First step is to find where is java installed. For that open terminal and type the below command

/usr/libexec/java_home
This command will output the location of java installation directory something like this depending upon the version of jdk installed
/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
Next step is to set PATH environment variable. Execute the below command in Terminal
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
export PATH=${PATH}:$JAVA_HOME/bin


 
 

Friday, September 5, 2014

New and Updated JSRs in JEE 7


Java EE 7 contains 14 new and updated JSRs. Java specifications are available at http://www.jcp.org.
  • JSR236:ConcurrencyUtilitiesforJavaEE1.0
  • JSR 338: Java Persistence API 2.1
  • JSR339:JavaAPIforRESTfulWebServices2.0
  • JSR 340: Java Servlet 3.1
  • JSR 341: Expression Language 3.0
  • JSR342:JavaPlatform,EnterpriseEdition7
  • JSR 343: Java Message Service 2.0
  • JSR 344: JavaServer Faces 2.2
  • JSR 345: Enterprise JavaBeans 3.2
  • JSR346:ContextsandDependencyInjectionforJavaEE1.1
  • JSR 349: Bean Validation 1.1
  • JSR352:BatchApplicationsfortheJavaPlatform1.0
  • JSR353:JavaAPIforJSONProcessing1.0
  • JSR356:JavaAPIforWebSocket1.0 

Thursday, March 27, 2014

Regular Expressions Reference Card


Title Reference Explanation Example Matches
Letters Inside Square Brackets [Ww] W or w [Ww]oodwork Woodwork, woodwork

[1234567890] Any digit






Letters outside square brackets ame Matches exact sequence ame -> amersohail794 matches ame





Ranges [0-9] 0 to 9 [0-2] -> amersohail794 matches 794

[a-z] all characters from a to z [a-z] -> amersohail794 matches amersohail

[A-Z] all characters from A to A [a-z] -> amersohail794 matches nothing

[ ] matches space [] -> amer sohail matches space only





Not [^a-z] Not characters from a-z [^a-z] matches 794

[^a-aA-Z] Not characters from a-z and from A-Z [^a-zA-Z] -> amersohail794 matches 794





Beginning of line ^ carret outside the square bracket shows that following character should be matched beginning of the line ^o -> oooohhhh OOOOhhh oooOOOOHHHH will match to first character only and that is "o"





End of line $ $ will match end of the line






Pipe Symbol | for or. A|a is same as [aA] W|w matches W or w





Special Characters *  0 or more occurences of previous character o*O*h*  matches oohhh, ooooooooohhhhh,OOOOOhhhhhh,oooOOOOOhhhhh

+ 1 or more occurences of previous character


? 0 or 1 occurrence of previous character


. Any character


\ is used as escape character [\.] -> This is sample sentence. will match the . In the line

Tuesday, January 28, 2014

Java Programming Terms

 Functional Interface

Its new term in JavaSE 8 for interfaces having just one method e.g. Runnable, ActionListener, Comparator, all are the examples of functional interfaces. Previous name was Single Abstract Method Type (SAM).

Anonymous Inner Classes

Its on the spot implementation of interface without explicitly requiring a name. Usually implementation of interfaces is done by classes and each class does have name but anonymous inner class does not have any name

Lambda Expressions

Short hand or concise notation for implementing functional interfaces than anonymous inner classes.

Immutable and Mutable Objects

Immutable objects are those objects which can not be changed after its creation. String is most famous example of immutable object. There are many pros of immutable objects like they can not be corrupted by multiple threads in concurrent application, least overhead for GC

Guarded Blocks

Its a code block waiting for a certain condition to be true for its execution. It happens in multi threading programs when different threads do different task and they coordinate each other by setting certain conditions / variables.

Generic Type

Generic Type is a generic class or interface that is parametrized over types.

Generic Type Declaration

 Definition of a class with type variables is know as Generic Type Declaration. This type variable can be used anywhere within a class.

The Diamond

In Java SE 7, we can replace the type arguments required to invoke a generic class, with empty set of type arguments (<>) as long as the compiler can determine or infer the type arguments from the content. This pair of angle brackets is known as "the diamond".

Box integerBox = new Box<>();
 
Raw Type
A Generic Class or interface without type arguments is known as raw type. e.g. List is a generic type but simple List is a raw type. We can assign generic types to raw types but assignment of raw type to generic type will give warnings and will be checked at runtime.
 

Updating...

Friday, December 20, 2013

Create a KeyStore to save Secret Key

Secret key is used to encrypt and decrypt the strings like "password" and other secret information. KeyStore is the most secure place to keep secret key. 

Here are the main steps to create new key store and saving a secret key:
  • Get instance of KeyStore using KeyStore.getInstance method. It takes the name of the keystore
  • Once instance of KeyStore is available, load it as empty keyStore
  • Generate the secretKey and save it to keystore for future purposes.
    private final String KEYSTORE_TYPE = "JCEKS";
    private final String KEYSTORE_NAME = "CareKeyStore";
    private final String SECRET_KEY_NAME = "secretKeyAlias";
    private final String KEY_ALGO = "AES";

    private String final pwd ="mypass";

    KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
    ks.load (null,pwd.toCharArray());
    KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGO);
    keyGen.init(128);
    SecretKey secretKey = keyGen.generateKey();
    KeyStore.ProtectionParameter protParam =
                            new KeyStore.PasswordProtection(pwd.toCharArray());
    KeyStore.SecretKeyEntry skEntry =
                            new KeyStore.SecretKeyEntry(secretKey);
    ks.setEntry(SECRET_KEY_NAME, skEntry, protParam);
    java.io.FileOutputStream fos = null;
    try {
           fos = new java.io.FileOutputStream(KEYSTORE_NAME);
           ks.store(fos, pwd.toCharArray());
                       
     }catch(Exception ex){
           logger.error(null,ex);
                       
      }finally {
            if (fos != null) {
                  fos.close();
            }
      }






          

Thursday, July 4, 2013

JPA Reference Card

Collection of basic types



Tuesday, April 9, 2013

JSF 2 Tips & Techniques - JSF Messages, Resource Bundle, and Validation Messages

Overriding default JSF error / warning Messages

Message bundle is used to override jsf's default error / warning messages. Declare message-bundle in your faces-config.xml and write new messages for default keys. You can define list of JSF defined messages from JSF specification under "Localized Application Messages"

Resource Bundle

Localized Resource bundle is defined with resource-bundle tag inside faces-config at global level or it is defined at the page level with loadBundle tag. Define resource bundle properties file in src/main/resources folder (You use any pacakge hierarchy e.g. if you want to define your resource bundle something like com.abc.view.ResourceBundle.properties then you needed to define corresponding folder hierarchy in your resource folder which will be src/main/resources/com/abc/view/ResourceBundle.properties. 

After defining your resource bundle, register it either on the page through f:loadBundle tag or globally in faces-config file using resource-bundle tag. 

Then Use it in your page like #{rb['app.title']}

Validation Messages using Bean Validation API

If you want to override default messages of Bean validation api or want to introduce new messages, then create ValidationMessages.properties file at root level i.e. at src/main/resources folder.

Sunday, November 11, 2012

Spring Framework Pitfalls

UndeclaredThrowableException thrown

This exception may occur when you are manipulating exception and changing it to exception type thrown by your method using AfterThrownAdvice or Around Advice. You can correct it either making your custom exception a Runtime Exception or explicitly mark your method to throw custom exception using "throws" clause.

Inherited Methods are not being adviced

Suppose you are using inheritance and want to advice both inherited methods and new methods in child class and you will be surprised that advice is not working on inherited methods. Yes that's true, it does not work unless you specifically also include parent include to be adviced.

I will keep on updating it with my findings...

Wednesday, November 7, 2012

Google Services Authentication Using OAuth2

Google APIs use the OAuth 2.0 protocol for Authentication and authorization. Google supports several OAuth2.0 flows that cover common web server, JavaScript, device, installed application, and server to server scenarios.
Today we will discuss how to use OAuth 2.0 for installed application. In a very first step, you will have to register your application with google account. Here are the steps to register application:

  • Visit this https://code.google.com/apis/console with your google account and create Project. 
  • In services tab, select services which you want to use.
  • In API access tab, "Create an OAuth 2.0 client ID". Please make sure that you select correct Application Type which is "Installed application" in our case and Installed application type is "Other". When you have completed it, you will get following information "Client ID", "Client secret", "Redirect URIs". These information will be needed for authentication


For this project, you are needed following three types of libraries:

I will suggest to have a look at https://developers.google.com/accounts/docs/OAuth2 for general idea how OAuth2 authentication works. Here is the summary:
  • Register Your application with Google
  • Redirect a browser to a URL
  • Get the Response and parse token.
  • Send the Token to the Google API you wish to access.
Now create a java project in your favorite IDE and include above downloaded libraries in your project's classpath. Create a class and paste following code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javainnovations.google;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.ServiceException;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Amer
 */
public class GoogleAuthentication {
    
    private final String CLIENT_ID = "CLIENT_ID";
    private final String CLIENT_SECRET = "CLIENT_SECRETS";
    private List scopes;
    
    private NetHttpTransport transport;
    private JacksonFactory gsonFactory;
    
    private SpreadsheetService service;
    
    public GoogleAuthentication(){
        transport = new NetHttpTransport();
        gsonFactory = new JacksonFactory();
        
        scopes = new ArrayList();
        scopes.add("https://spreadsheets.google.com/feeds");
        scopes.add("https://docs.google.com/feeds");
    }
    
    
    public static void main(String args[]) throws IOException, MalformedURLException, ServiceException{
        GoogleAuthentication auth = new GoogleAuthentication();
        auth.init();
        auth.printWorkSheets();
    }
    
    public void init() throws IOException{
        Credential credential = authenticate();
        service = initSpreadsheetService(credential);
    }
    
    public Credential authenticate() throws IOException{
        GoogleAuthorizationCodeFlow.Builder builder = new GoogleAuthorizationCodeFlow.Builder(transport,gsonFactory,CLIENT_ID,CLIENT_SECRET,scopes);
        File cfile = new File("oauth2.json");
        cfile.createNewFile();
        FileCredentialStore credentialStore = new FileCredentialStore(cfile, gsonFactory);
        builder.setCredentialStore(credentialStore);
        GoogleAuthorizationCodeFlow flow = builder.build();
        return new AuthorizationCodeInstalledApp(flow, new LocalCallbackServer()).authorize("user");
    }
    
    public SpreadsheetService initSpreadsheetService(Credential credential) {
        SpreadsheetService service = new SpreadsheetService("MySpreadsheet");
        service.setOAuth2Credentials(credential);
        return service;
    }
    
    public void printWorkSheets()throws MalformedURLException, IOException, ServiceException{
        URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
        SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
        List spreadsheets = feed.getEntries();
        System.out.println("No of spreadsheets -> "+spreadsheets.size());

        
    }
    
}
Most Important method is "authenticate". Let's discuss it line by line:

  • In first line GoogleAuthorizationCodeFlow.Builder was used to input CLIENT_ID, CLIENT_SECRET, list of scopes. CLIENT_ID and CLIENT_SECRET is provided by google while registering the application
  • In next few lines, a FileCredentialStore is created. This will store the credentials info returned by google after authentication to a file and will be used later on to communicate to google services. Since its critical information so place it to some secure place like user's account folder in your operation system.
  • GoogleAuthorizationCodeFlow.Builder.build() method creates GoogleAuthorizationCodeFlow which will be input as a authentication info object to AuthorizationCodeInstalledApp class
  • AuthorizationCodeInstalledApp is mainly responsible to send request to google server for authentication with all credentials. Its constructor takes an object which implements VerificationCodeReceiver interface. Google will send code in a response to implementation of this interface. This will act as callback server. I have provided below a socket based test implementation. This is just for reference purpose.
  • Once code is received, it is sent to google again to get credential information containing access_code. which will be stored to file by FileCredentialStore as discussed above.
  • If everything goes fine, it will retrurn Credential object. This object is passed to Google Service object like SpreadhSheetService and in all further communication, this credential information will be exchanged with google server to authenticate request from valid user. See initService method for details. Rest of the thing is straight forward.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javainnovations.google;

import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Amer
 */
public class LocalCallbackServer implements VerificationCodeReceiver {

    volatile String code;
    private final int LOCAL_SERVER_PORT = 10006;

    @Override
    public synchronized String waitForCode() {

        try {
            this.wait();
        } catch (Exception ex) {
        }
        System.out.println("returning code is -> " + code);
        return code;

    }

    @Override
    public String getRedirectUri() {

        new Thread(new MyThread()).start();
        return "http://localhost:"+LOCAL_SERVER_PORT;
    }

    @Override
    public void stop() {
    }

    class MyThread implements Runnable {

        @Override
        public void run() {
            try {
                //    return GoogleOAuthConstants.OOB_REDIRECT_URI;
                ServerSocket ss = new ServerSocket(LOCAL_SERVER_PORT);
                System.out.println("server is ready...");
                Socket socket = ss.accept();
                System.out.println("new request....");
                InputStream is = socket.getInputStream();
                StringWriter writer = new StringWriter();
                String firstLine = null;

                InputStreamReader isr = new InputStreamReader(is);
                StringBuilder sb = new StringBuilder();
                BufferedReader br = new BufferedReader(isr);
                String read = br.readLine();
                firstLine = read;
                OutputStream os = socket.getOutputStream();
                PrintWriter out = new PrintWriter(os, true);
                
                StringTokenizer st = new StringTokenizer(firstLine, " ");
                st.nextToken();
                String codeLine = st.nextToken();
                st = new StringTokenizer(codeLine, "=");
                st.nextToken();
                code = st.nextToken();
                
                out.write("RETURNED CODE IS "+code+"");
                out.flush();
//                is.close();
                
                socket.close();

                
                System.out.println("Extracted coded is " + code);

                synchronized (LocalCallbackServer.this) {
                    LocalCallbackServer.this.notify();
                }
                System.out.println("return is " + sb.toString());

            } catch (IOException ex) {
                Logger.getLogger(LocalCallbackServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}


Tuesday, October 30, 2012

Registering Custom JSF Renderer

JSF has a very flexible architecture by providing hooks to plugin custom implementation for components, renderers, converters, validators etc. Today i will discuss the way to plugin own renderer without touching any other thing. Usually in every application, there are some properties which are set for ui components in order to make look & feel consistent throughout the application and these properties are set on each page for components. If we override renderer and set these properties as default properties, a lot of burden from developers end is removed. Moreover, it will also provide an easy way to change it in future at a single point instead of each page, so this is very handly thing to provide own renderers.
I am overriding a renderer for input text component of Prime faces. This renderer will not do anything special and will just print a statement on console. Here are the steps to follow:

  • First override the renderer of the component in which we want to provide custom rendering. Prime faces' User guide is an excellent reference source for each component e.g. for InutText, you will find all information about component's implementation classes and you will find there that org.primefaces.component.inputtext.InputTextRenderer is a default renderer for prime faces' input text component.



  • Create a custom renderer class which will extend above renderer and override the method in which you want to provide custom implementations. You can also download source code and can study default implementation of renderer. It will provide you good understanding how to do things. Sample implementation is given below:
     public class MyInputTextRenderer extends InputTextRenderer{
    @Override
     protected void encodeMarkup(FacesContext context, InputText inputText) throws IOException {
        System.out.println("encodemarkup");
        super.encodeMarkup(context, inputText);
    }
    }
              • Third and last thing is to register this custom renderer in jsf application. For that you will have to provide following entries in faces-config.xml:

                 
              component-family and renderer-type will help framework to understand for which component, custom renderer will be used

                          Saturday, October 6, 2012

                          Maven Tips


                          • When we include a jar dependency in pom.xml. That jar may intern depend on other jars and maven resolve it and loads all jars whether those are directly indicated as dependent jars or indirectly within dependent jars. Now if we have some latest version or any other reason and want to exclude a particular jar to be included as dependent then maven provides "exclusions" element tag. Its sample usage is given below:
                          <dependency>
                          <groupId>org.hibernate</groupId>
                          <artifactId>hibernate-core</artifactId>
                          <version>4.1.7.Final</version>
                          <scope>provided</scope>
                          <exclusions>
                                <exclusion>
                                   <groupId>org.antlr</groupId>
                                   <artifactId>antlr</artifactId>
                                </exclusion>
                             </exclusions>
                          </dependency>

                          In above example, exclusions tag used to exclude antlr jar file to be included as dependent jar for hibernate

                          continued...

                          Monday, November 14, 2011

                          Common ADF Mistakes - Conversion pages to page fragments

                          Suppose you have developed ADF task flow with pages (not page fragments) and later on you decide that these pages should be page fragments, and you convert that taskflow to support page fragments. After conversion, if you get this error
                          java.lang.IllegalStateException: Attempt to validate an already invalid RegionSite:
                          Check whether you have used PageController for page or not. If you used then convert it to RegionController. ADF does not give you indication of this. If you want to debug error, do the following:
                          • Goto bindings of page on which you dropped taskflow containing page fragments.
                          • In Executables, click the taskflow and set its property "activation" to "immediate"
                          • Now run and you will get detailed error.
                          Update

                          It can also occur if your taskflow is calling any method before page loading and that method is throwing some error.

                          Sunday, March 13, 2011

                          JSF 2 Internals - Efficient way of Redirecting to a Page

                          There are certain cases where you are needed to redirect  to a different page than requested by user e.g. if user has requested a secure page for which he/she is not authorized, your application will have to redirect to login page or some other page. I have created a utility method to redirect to a page. You can call anywhere but for example given above, you can call it a beforePhase method of RestoreViewPhaseListener. Here is the method code:

                          public static void redirect(String viewId) {

                          execute(FacesContext.getCurrentInstance(), viewId);
                          }


                          private static void execute(FacesContext facesContext, String viewId)
                          throws FacesException {

                          UIViewRoot viewRoot = null;
                          ViewDeclarationLanguage vdl = facesContext.getApplication()
                          .getViewHandler()
                          .getViewDeclarationLanguage(facesContext, viewId);

                          if (vdl != null) {
                          // If we have one, get the ViewMetadata...
                          ViewMetadata metadata = vdl.getViewMetadata(facesContext,
                          viewId);

                          if (metadata != null) { // perhaps it's not supported
                          // and use it to create the ViewRoot. This will have, at
                          // most
                          // the UIViewRoot and its metadata facet.
                          viewRoot = metadata.createMetadataView(facesContext);

                          }
                          }

                          facesContext.setViewRoot(viewRoot);
                          facesContext.renderResponse();
                          assert (null != viewRoot);

                          }

                          viewId is the name of page to which it should redirect e.g. "/redirect.xml" (assuming page is at root level). Inside execute method, you get the ViewDeclarationLanguage which is page type specific e.g. if page is in facelet markup, you get DefaultFaceletViewDeclarationLanguage and if page is in JSP markup, then you will get corresponding ViewDeclarationLanguage. After this, page root tree is constructed by calling createMetadataView if it is not already constructed. Finally set the new ViewRoot and call renderResponse method, which will bypass all phases and will jump directly to render phase.

                          Tuesday, March 8, 2011

                          JSF 2 Internals - Configurations

                          In JSF 2, there is almost no need to mention any configuration in a small application and defaults values are sufficient enough to fulfill the purpose. All the default configurations are in com.sun.faces.WebConfiguration. As i mentioned in my previous blog post, JSF has implemented ServletContainerInitializer which is new interface in Servlet 3.0 in order to register servlets and other stuff programmatically at the time of loading application. In 'onStartUp' method, it adds listener com.sun.faces.ConfigureListener. It implements various interface listeners like ServletRequestListener, HttpSessionListener, ServletContextListener, ServletRequestAttributeListener, HttpSessionAttributeListener, ServletContextAttributeListener. Most important for loading configuration is ServletCotextListeenr which has two methods contextInitialized and contextDestroyed. contextInitialized  is called when application loads and ServletContext is created, so this is the best time to load configurations in JEE web applications. JSF 2 also gets benefit of this and creates WebConfiguration Object and loads default values for configurations. If application has its own values mentioned in web.xml, they are overriden.

                          Wednesday, March 2, 2011

                          JSF 2 Internals - Entry of FacesServlet is optional

                          In JEE 6, major milestone achieved was reduction of configuration files e.g. in servlet based web application, no need to mention web.xml and application assumes default configuration settings. Same thing was also achieved in JSF 2. Now there is no need to mention FaceServlet or servlet mapping in web.xml. But question arises from where application picks these defaults? Answer is the "ServletContainerInitializer" interface which allows a library/runtime to be notified of a web application's startup phase and perform any required programmatic registration of servlets,filters, and listeners in response to it. Inside of "onStartup" implementation of JSF 2, all these defaults are set, Sample code is given below:
                          ServletRegistration reg =
                          servletContext.addServlet("FacesServlet",
                          "javax.faces.webapp.FacesServlet");
                          reg.addMapping("/faces/*", "*.jsf", "*.faces");
                          servletContext.setAttribute(RIConstants.FACES_INITIALIZER_MAPPINGS_ADDED, Boolean.TRUE);
                          JSF 2 class which implements this interface is "FacesInitializer" class and have been mentioned under jsf-ri.jar's META-INF/services folder.



                          Thursday, February 24, 2011

                          Learning IOS Programming for Java Developers - Memory Management in Setters and Getters Of Object

                          Encapsulation is one of the basic building block in Object Oriented paradigm. Encapsulation in Java is achieve by restricting user to directly access the fields of Object and in order to access those fields, setters and getters are written. Objective C is also an object oriented programming language and also provides encapsulation by providing setters and getters to access the object data. Here is the sample class which contains two fields. One is an object and second one is of basic data type.
                          @interface TestClass : NSObject
                          {
                          NSString *name;
                          int id;
                          }

                          - (void) setName : (NSString *) newName;
                          - (NSString *) name;

                          - (void) setId : (int) newId;
                          - (int) id;

                          "setName" and "name" is setter and getter of "name" field. Similarly "setId" and "id" id setter and getter of "id" field.

                          Here is the implementation part of class
                          @implementation TestClass
                          {
                          - (void) setName : (NSString *) newName
                          {
                          [newName retain];
                          [name release];
                          name = newName;
                          }

                          - (NSString *) name
                          {
                          return name;
                          }
                          - (void) setId : (int) newId
                          {
                          id = newId;
                          }

                          - (int) id
                          {
                          return id;
                          }


                          }

                          setName needs your special intention for memory management point of view. First you send message "retain" to parameter, then you release old field by sending message "release" to name pointer. Then you assign new value to name pointer. These three steps are critical because if you change the order like you release old one and then retain new parameter, if both are same, then by sending release message will free the memory and new parameter will also be freed because that was same as old one. By sending retain message to parameter, you actually gain ownership of it and its reference count increases. Since you have also ownership of old one, so you will have to release it otherwise you will lose reference and there will be memory leak. Now as a java developer i can think that if "name" field is null, then sending release message may give something like NullPointerException but in Objective C, sending a message to null is safe and it will not throw any error and will keep executing next line.
                          Now last thing which is missing is that how to release fields which are retained before releasing object memroy, so for that you will have to overwrite a special method of NSObject "dealloc". This method is called when you send release message to an object and its reference count is 0. In this method you will have to release all those objects which you have retained. Sample implementation for above class is given below:
                          - (void) dealloc
                          {
                          [name release];
                          [super dealloc];
                          }


                          Wednesday, February 23, 2011

                          How to Learn IOS Programming having experience In Java language

                          I am creating this post to help those which are working in java programming language and want to explore or work in IOS. I am working in Java for last eight years and now exploring IOS programming so will share my experiences through this post.

                          Monday, February 7, 2011

                          Setting datasource name programmatically for ADF Application

                          While working on an enterprise application for my client, i received a request from the client that data source name should not be hardcoded in the application and it should be configurable because client wants to deploy it more than one instance of application on the same server for different purposes like preview, production etc. So i googled it, and found excellent article 11g Dynamic JDBC Credentials for Model 1, Struts, Trinidad, and ADF Faces Rich Client
                          Here it is simplified version:
                          You will have to extend two following classes:

                          • EnvInfoProvider
                          • DefaultSessionCookieFactory

                          EnvInfoProvider
                          This is main interface and datasource name will be set in the implementation of this interace. You will have to implement following three methods:

                          • public Object getInfo(String propName, Object object)
                          • public void modifyInitialContext(Object initialContext)
                          • public int getNumOfRetries()
                          Only important method for our scenario is getInfo method. It is used to set new datasource name. Sample implementation is given below:

                          public Object getInfo(String propName, Object object) {
                          String myDataSourceName = "test"; // You can set it through your logic
                          if (object instanceof Hashtable) {
                          Hashtable connectionEnv = (Hashtable)object;
                          System.out.println(connectionEnv.get(Configuration.JDBC_CONNECTION_NAME));
                          String contextPath = (String)ADFContext.getCurrent().getSessionScope().get("contextPath");
                          connectionEnv.put(Configuration.JDBC_DS_NAME,"java:comp/env/jdbc/"+myDataSourceName );
                          }
                          return null;
                          }

                          public void modifyInitialContext(Object initialContext) {
                          }

                          public int getNumOfRetries() {
                          return 0;
                          }

                          DefaultSessionCookieFactory
                          In order to configure custom implementation of EnvInfoProvider, you will have to extend DefaultSessionCookieFactory and override createSessionCookie method. Sample implementation is given below:
                          public SessionCookie createSessionCookie(String name,
                          String value,
                          ApplicationPool pool,
                          Properties properties) {

                          SessionCookie cookie = super.createSessionCookie(name, value, pool, properties);
                          Hashtable env = pool.getEnvironment();

                          env.remove(Configuration.JDBC_CONNECTION_NAME);
                          EnvInfoProvider provider = new MyEnvInfoProvider();
                          cookie.setEnvInfoProvider(provider);
                          return cookie;
                          }
                          Now last step is to configure this custom SessionCookieFactory. Open bc4j.xcfg of application module and add following element as a child of respected AppModuleConfig element

                          Thursday, July 29, 2010

                          Accessing Runtime metadata for ViewObject and EntityObject


                          In Oracle ADF, ViewObject and EntityObject are two basic concepts and whole application revolves around these two type of objects. EntityObject corresponds to database table while ViewObject corresponds to Database View. ViewObject can be based on EntityObject, SQL or on transient attributes. Normally you create and design these two objects throug drag and drop in JDeveloper but sometimes you need some meta information about these two objects in business logic. In order to get metainfo, some understanding of underlying structure of these two objects should be.
                          Figure shown above illustrates the three primary interfaces ADF provides for accessing runtime metadata about view objects and entity objects. The ViewObject interface extends the StructureDef interface. The class representing the entity definition (EntityDefImpl) also implements this interface. As its name implies, the StructureDef defines the structure and the component and provides access to a collection of AttributeDef objects that offer runtime metadata about each attribute in the view object row or entity row. Using an AttributeDef, you can access its companion AttributeHints object to reference hints like the display label, format mask, tooltip, etc.
                          Now you can use this understanding to get runtime meta info about view object or entity object e.g. if i want to find whether a ViewObject is readonly non entity based object or not. i can find it by:

                          • isFullSql() is true

                            This method returns true if the view object's SQL query is completely specified by the developer, as opposed to having the select list derived automatically based on the participating entity usages.

                          • getEntityDefs() is null

                            This method returns an array of EntityDefImpl objects representing the view object's entity usages. If it returns null, then the view object has no entity usages.