Saturday, September 10, 2011

Module Loader along with Context Management in Parsley Framework in Flex 4

Please click on any advertisement on right side if you like this blog.

Parsley is a flex framework that provides the facility like Injections, Messaging, and View Wiring etc. The injection mechanism is very much similar to IOC mechanism of Java Spring Framework. Here, we are going to discuss the process for maintaining the injection mechanism in child modules while loading into a parent project.

Scenario:
1)      Create a project with parsley framework implementation and use injection in that project.
2)      Create a module in that project and write code for injecting model object in that module.
3)      Create another project and also use parsley injection mechanism to create object of a model class in that project.
4)      Write code in this new project for loading module created in step 1 and step 2.

Observation:
1)      Module should be loaded in main project.
2)      Injection in module class and main project after module loading must work similarly as before module loading.

Code:
Code for creating the module:
Module1.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:fx="http://ns.adobe.com/mxml/2009"
                     xmlns:s="library://ns.adobe.com/flex/spark"
                     xmlns:mx="library://ns.adobe.com/flex/mx"
                     xmlns:sf="http://www.spicefactory.org/parsley"
                     minWidth="955" minHeight="600">
     
      <fx:Script>
            <![CDATA[
                  import models.Module1model;
                 
                  [Inject]
                  public var module1Model:Module1model;
                 
                  private function handleClick():void
                  {
                        this.textContainer.text = module1Model.printMessage();
                  }
            ]]>
      </fx:Script>
     
      <fx:Declarations>
            <sf:ContextBuilder>
                  <sf:XmlConfig file="Config.xml"/>
            </sf:ContextBuilder>
            <sf:Configure/>
      </fx:Declarations>
     
      <s:VGroup id="mod1Vgroup">
            <s:Button label="Print Message in Module1" id="printTextBtn" click="handleClick();"/>
            <s:Button label="Clear Text" id="clearTextBtn" click="{this.textContainer.text = ''}"/>
            <s:Label text="Message Board"/>
            <s:TextArea id="textContainer"/>
      </s:VGroup>
     
</mx:Module>

Please click on any advertisement on right side if you like this blog.

Config file for this module
ModuleConfig.xml

<objects
    xmlns="http://www.spicefactory.org/parsley"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.spicefactory.org/parsley
        http://www.spicefactory.org/parsley/schema/2.3/parsley-core.xsd"
    >
     
      <object type="models.Module1model" id="module1"/>
     
</objects>


Up to now we have covered the steps 1 and 2 of scenario discussed above. Now let’s create a project in which this module is to be loaded as stated in step 3.

Suppose we have created a new project say MainProject as stated above. Now, let’s write code for loading module in main project as stated in step 4 in scenario.

To load the newly created module in our main project we have to follow following steps:
1)    Copy the corresponding swf file and xml file(used as config file) from the binDebug folder of module project and paste these in binDebug folder of main project where these have to be loaded.
2)    Write code for loading the corresponding module in main project.

Suppose we have followed and step 1 as discussed above. And now, we have to write code for loading module in main project. Say, we have written this code in MainProject.mxml as follows:

MainProject.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                     xmlns:s="library://ns.adobe.com/flex/spark"
                     xmlns:mx="library://ns.adobe.com/flex/mx"
                     xmlns:sf="http://www.spicefactory.org/parsley"                   
                     addedToStage="dispatchEvent(new Event('configureIOC', true))"
                     minWidth="955" minHeight="600">
      <fx:Script>
            <![CDATA[
                  import models.MainModuleModel;
                 
                  import mx.controls.Alert;
                  import mx.core.IVisualElement;
                  import mx.events.ModuleEvent;
                  import mx.modules.IModuleInfo;
                  import mx.modules.ModuleManager;
                 
                  [Inject(id="mainModuleModel")]
                  public var mainModuleModel:MainModuleModel;                
                 
                  public function handleClick():void
                  {                      
                        this.mainModuleText.text = mainModuleModel.printMessage(); 
                  }
                                   
                  private function initApp():void {
                        md1.url = "Module1.swf";
                        //md1.applicationDomain =
                        md1.loadModule();
                       
                  }
                 
                  /* Add an instance of the module's class to the display list. */
                  public function modEventHandler(e:Event=null):void {
                        Alert.show("in mod event in module1");
                  }
                  public function handleError(e:Event):void {
                        Alert.show("error");
                  }
                 
                  public function handleProgress(e:Event):void{
                        Alert.show("testdf");
                  }
                 
                  [Init]
                  public function init():void{
                        this.mainModuleText.text =    mainModuleModel.printMessage();
                       
                        initApp();
                  }                
            ]]>
      </fx:Script>
     
      <fx:Declarations>
            <sf:ContextBuilder>
                  <sf:XmlConfig file="main.xml"/>
            </sf:ContextBuilder>
      </fx:Declarations>
     
      <s:Label id="mainModuleText"/>
     
      <s:HGroup gap="100">
            <mx:ModuleLoader id="md1" ready="modEventHandler();" />
      </s:HGroup>
     
</s:Application>


If we follow these steps accordingly, the corresponding module will be loaded in Main Project and the injection mechanism of both module and Main project will work as needed.

For complete code, please write to me at “jksnu1@gmail.com”

Please click on any advertisement on right side if you like this blog.

Interview Questions: JDBC : Volume 3

Q. Can ResultSets be passed between methods of a class? Are there any special usage                       
Yes. There is no reason that a ResultSet can't be used as a method parameter just like any other object reference. You must ensure that access to the ResultSet is synchronized. This should not be a problem is the ResultSet is a method variable passed as a method parameter - the ResultSet will have method scope and multi-thread access would not be an issue.

As an example, say you have several methods that obtain a ResultSet from the same table(s) and same columns, but use different queries. If you want these ResultSets to be processed the same way, you would have another method for that. This could look something like:
public List getStudentsByLastName(String lastName) {
ResultSet rs = ... (JDBC code to retrieve students by last name);
return processResultSet(rs);
}

public List getStudentsByFirstName(String firstName) {
ResultSet rs = ... (JDBC code to retrieve students by first name);
return processResultSet(rs);
}

private List processResultSet(ResultSet rs) {
List l = ... (code that iterates through ResultSet to build a List of Student objects);
return l;
}


Since the ResultSet always has method scope - sychronization is never an issue.

1. There is only one ResultSet. Dont assume that the ResultSet is at the start (or in any good state...) just because you received it as a parameter. Previous operations involving the ResultSet will have had the side-effect of changing its state.
2. You will need to be careful about the order in which you close the ResultSet and CallableStatement/PreparedStatement/etc

From my own experience using the Oracle JDBC drivers and CallableStatements the following statements are true:

* If you close the CallableStatement the ResultSet retrieved from that CallableStatement immediately goes out-of-scope.
* If you close the ResultSet without reading it fully, you must close the CallableStatement or risk leaking a cursor on the database server.
* If you close the CallableStatement without reading it's associated ResultSet fully, you risk leaking a cursor on the database server.

No doubt, these observations are valid only for Oracle drivers. Perhaps only for some versions of Oracle drivers.

The recommended sequence seems to be:
* Open the statement
* Retrieve the ResultSet from the statement
* Read what you need from the ResultSet
* Close the ResultSet
* Close the Statement 

Q. What is Metadata and why should I use it?                                                                                        Metadata ('data about data') is information about one of two things:
1. Database information (java.sql.DatabaseMetaData), or
2. Information about a specific ResultSet (java.sql.ResultSetMetaData).

Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns.                                                                                                                                                 
 
Please click on any advertisement on right side if you like this blog.
Q. How to Retrieve Warnings ?                                                                                                                
ans:--     SQLWarning  objects are a subclass of SQLException that deal with database access warnings.                                                                                                                                                             Warnings do not stop the execution of an application, as exceptions do; they simply alert the          user that something did not happen as planned. For example, a warning might let you know that a         privilege you attempted to revoke was not revoked. Or a warning might tell you that an error occurred during a requested disconnection.A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object. If getWarnings returns a warning, you can call the SQLWarning method getNextWarning on it to get any additional warnings. Executing a statement automatically clears the warnings from a previous statement, so they do not build up. This means, however, that if you want to retrieve warnings reported on a statement, you must do so before you execute another statement.The following code fragment illustrates how to get complete information about any warnings reported on the Statement object stmt and also on the ResultSet object rs 
Statement stmt = con.createStatement();                                                                                               ResultSet rs = stmt.executeQuery("select COF_NAME from COFFEES");                                                                    
while (rs.next()) 
{                                                                                                                                             
String coffeeName = rs.getString("COF_NAME");
            System.out.println("Coffees available at the Coffee Break:  ");
            System.out.println("    " + coffeeName);
            SQLWarning warning = stmt.getWarnings();
            if (warning != null) {
                        System.out.println("\n---Warning---\n");
                        while (warning != null) {
                                    System.out.println("Message: "
                                                   + warning.getMessage());
                                    System.out.println("SQLState: "
                                                   + warning.getSQLState());
                                    System.out.print("Vendor error code: ");
                                    System.out.println(warning.getErrorCode());
                                    System.out.println("");
                                    warning = warning.getNextWarning();
                        }
            }
            SQLWarning warn = rs.getWarnings();
            if (warn != null) {
                        System.out.println("\n---Warning---\n");
                        while (warn != null) {
                                    System.out.println("Message: "
                                                   + warn.getMessage());
                                    System.out.println("SQLState: "
                                                   + warn.getSQLState());
                                    System.out.print("Vendor error code: ");
                                    System.out.println(warn.getErrorCode());
                                    System.out.println("");
                                    warn = warn.getNextWarning();
                        }
            }
        }
            Warnings are actually rather uncommon. Of those that are reported, by far the most common warning is a DataTruncation warning, a subclass of SQLWarning. All DataTruncation objects have an SQLState of 01004, indicating that there was a problem with reading or writing data. DataTruncation methods let you find out in which column or parameter data was truncated, whether the truncation was on a read or write operation, how many bytes should have been transferred, and how many bytes were actually transferred


Please click on any advertisement on right side if you like this blog.

Interview Questions : JDBC : Volume 2

Q. How to update a resultset programmatically? (new feature in JDBC 2.0)                                                         
a. create a scrollable and updatable ResultSet object.                                                                                               
Statement stmt = con.createStatement          (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);                              ResultSet uprs = stmt.executeQuery("SELECT   COLUMN_1,                                   
COLUMN_2 FROM TABLE_NAME");  
b. move the cursor to the specific position and use related method to update data and then, call updateRow() method.                                                                                                                                              uprs.last();                                                 uprs.updateFloat("COLUMN_2", 25.55);//update last row's data    uprs.updateRow();
//don't miss this method, otherwise, the data will be lost.                                                

Q. How to insert and delete a row programmatically? (new feature in JDBC 2.0)                                  Make sure the resultset is updatable. 
                                                         
1. move the cursor to the specific position.                     
uprs.moveToCurrentRow();  

2.Set value for each column                                              uprs.moveToInsertRow();//to set up for insert                    
uprs.updateString("col1","strvalue"); 
uprs.updateInt("col2",5);                                                                                                                                             
3.call inserRow() method to finish the row insert process.   uprs.insertRow();                                                         
 To delete a row: move to the specific position and call deleteRow() method:                  uprs.absolute(5);                                                                       uprs.deleteRow();//delete row 5              

To see the changes, call 
refreshRow(); 
uprs.refreshRow(); 
 
Q. What are the common tasks of JDBC?                   
Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
Register a driver
Specify a database
Open a database connection
Submit a query
Receive results
Process results 

Please click on any advertisement if you like this blog.

 
Q. How can I know when I reach the last record in a table, since JDBC doesn't provide an EOF method?                                                                                                                                                      Answer1
You can use last() method of java.sql.ResultSet, if you make it scrollable.
You can also use isLast() as you are reading the ResultSet.
One thing to keep in mind, though, is that both methods tell you that you have reached the end of the current ResultSet, not necessarily the end of the table. SQL and RDBMSes make no guarantees about the order of rows, even from sequential SELECTs, unless you specifically use ORDER BY. Even then, that doesn't necessarily tell you the order of data in the table.

Answer2
Assuming you mean ResultSet instead of Table, the usual idiom for iterating over a forward only resultset is:
ResultSet rs=statement.executeQuery(...);
while (rs.next()) {
// Manipulate row here
}                                                                                                                                                                                 
Q. How can I insert images into a Mysql database?                                                                               This code snippet shows the basics:
File file = new File(fPICTURE);
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps =
ConrsIn.prepareStatement("insert into dbPICTURE values (?,?)");

// ***use as many ??? as you need to insert in the exact order***
ps.setString(1,file.getName());
ps.setBinaryStream(2,fis,(int)file.length());
ps.close();
fis.close();

Q. How do I check in my code whether a maximum limit of database connections have been reached?                                                                                                                                         
 Use DatabaseMetaData.getMaxConnections() and compare to the number of connections currently open. Note that a return value of zero can mean unlimited or, unfortunately, unknown. Of course, driverManager.getConnection() will throw an exception if a Connection can not be obtained. 

Please click on any advertisement on right side if you like this blog.


Q. What is the difference between setMaxRows(int) and SetFetchSize(int)? Can either reduce processing time?                                                                                                                              setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. The method in the java.sql.Statement interface will set the 'default' value for all the ResultSet derived from that Statement; the method in the java.sql.ResultSet interface will override that value for a specific ResultSet. Since database fetches can be expensive in a networked environment, fetch size has an impact on performance.
setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRows method may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit.
Since we're talking about interfaces, be careful because the implementation of drivers is often different from database to database and, in some cases, may not be implemented or have a null implementation. Always refer to the driver documentation. 


Q.What's the best way, in terms of performance, to do multiple insert/update statements, a PreparedStatement or Batch Updates?                                                                                               Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency.
A CallableStatement object provides a way to call stored procedures in a standard manner for all DBMSes. Their execution can be faster than that of PreparedStatement object.
Batch updates are used when you want to execute multiple statements together. Actually, there is no conflict here. While it depends on the driver/DBMS engine as to whether or not you will get an actual performance benefit from batch updates, Statement, PreparedStatement, and CallableStatement can all execute the addBatch() method. 


Q.What is the difference between setMaxRows(int) and SetFetchSize(int)? Can either reduce processing time?                                                                                                                       
 setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. The method in the java.sql.Statement interface will set the 'default' value for all the ResultSet derived from that Statement; the method in the java.sql.ResultSet interface will override that value for a specific ResultSet. Since database fetches can be expensive in a networked environment, fetch size has an impact on performance.
setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRows method may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit.
Since we're talking about interfaces, be careful because the implementation of drivers is often different from database to database and, in some cases, may not be implemented or have a null implementation. Always refer to the driver documentation. 


Please click on any advertisement if you like this blog.


Q. What's the best way, in terms of performance, to do multiple insert/update statements, a PreparedStatement or Batch Updates?                                                                                                         Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency.
A CallableStatement object provides a way to call stored procedures in a standard manner for all DBMSes. Their execution can be faster than that of PreparedStatement object.
Batch updates are used when you want to execute multiple statements together. Actually, there is no conflict here. While it depends on the driver/DBMS engine as to whether or not you will get an actual performance benefit from batch updates, Statement, PreparedStatement, and CallableStatement can all execute the addBatch() method. 

Q. What is the advantage of using a PreparedStatement?                                                                       For SQL statements that are executed repeatedly, using a PreparedStatement object would almost always be faster than using a Statement object. This is because creating a PreparedStatement object by explicitly giving the SQL statement causes the statement to be precompiled within the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement and prepared an execution plan - it simply runs the statement.
Typically, PreparedStatement objects are used for SQL statements that take parameters. However, they can also be used with repeatedly executed SQL statements that do not accept parameters. 




Please click on any advertisement on right side if you like this blog.

Interview Questions : JDBC : Volume 1

Please click on any advertisement on right side if you like this blog.
JDBC Question

Q. JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

4 types of jdbc drivers are elaborated in detail as shown below:

Type 1 JDBC Driver

JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.

Advantage : The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. 

Disadvantages: 1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

Type 2 JDBC Driver: Native-API/partly Java driver                                                                            
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.


 Advantage : The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.     
                                                   
Disadvantage : 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.     
                                
Please click on any advertisement on right side if you like this blog.
                                                                                       
Type 3 JDBC Driver : All Java/Net-protocol driver                                                                                                   
Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.  

 
Type 3: All Java/ Net-Protocol Driver                                                                                                 Advantage : 1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantage : It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

Type 4 JDBC Driver : Native-protocol/all-Java driver                                                                     

The Type 4 uses java networking libraries to communicate directly with the database server.

Advantage : 1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.
Disadvantage :
With type 4 drivers, the user needs a different driver for each database. 


Please click on any advertisement if you like this blog.

Q.What is new in JDBC 2.0?                                                                                                                          
With the JDBC 2.0 API, you will be able to do the following:
  • Scroll forward and backward in a result set or move to a specific row (TYPE_SCROLL_SENSITIVE,previous(), last(), absolute(), relative(), etc.)
  • Make updates to database tables using methods in the Java programming language instead of using SQL commands.(updateRow(), insertRow(), deleteRow(), etc.)
  • Send multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch())
  • Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.
Q. How to move the cursor in scrollable resultsets?(new feature in JDBC 2.0)                                             a. create a scrollable ResultSet object.                                                                                                                
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,         ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COLUMN_1, COLUMN_2 FROM TABLE_NAME");   
                                                          
 b. use a built in methods like afterLast(), previous(), beforeFirst(), etc. to scroll the resultset.          

srs.afterLast();         
while (srs.previous()) 
   {                                                                     
       
      String name = srs.getString("COLUMN_1"); 
      float salary = srs.getFloat("COLUMN_2");                                     //...      
                                                                               
c. to find a specific row, use absolute(), relative() methods.                                                        
srs.absolute(4); // cursor is on the fourth row

int rowNum = srs.getRow(); // rowNum should be 4       srs.relative(-3);    
int rowNum = srs.getRow(); // rowNum should be 1
srs.relative(2);
int rowNum = srs.getRow(); // rowNum should be 3 
                                
d. use isFirst(), isLast(), isBeforeFirst(), isAfterLast() methods to check boundary status.
Please click on any advertisement on right side if you like this blog.