tag:blogger.com,1999:blog-70343925814939496582024-03-08T04:44:36.914-08:00Monika's BlogsMonika Mishrahttp://www.blogger.com/profile/06161978834743976151noreply@blogger.comBlogger6125tag:blogger.com,1999:blog-7034392581493949658.post-12557003553135331082009-12-06T00:04:00.000-08:002009-12-06T00:07:36.586-08:00<p align="CENTER" style="margin-bottom: 0in"><span style="font-size:130%;">Performance tuning with Hibernate – Understanding fetching strategies</span></p> <p align="CENTER" style="margin-bottom: 0in"><br /></p> <p align="LEFT" style="margin-bottom: 0in"><span style="font-size:100%;">Sky is the limit when it comes to improve the performance of a hibernate based application. But before jumping to using second level cache, terrcotta etc., there are a few things we need to look at first. Below are a few lessons learned from experience →</span></p> <p align="LEFT" style="margin-bottom: 0in"><span style="font-size:100%;">Choose the right fetching strategy:</span></p> <p align="LEFT" style="margin-bottom: 0in"><span style="font-size:100%;"> It is very important to understand how hibernate issues SQLs to the DB for different fetching strategies. If hibernate issues too many queries to the database, it can cause significant performance degradation. Let's take an example of department and employee relationsh</span><span><span class="Apple-style-span" style="font-size: medium;">i</span><span class="Apple-style-span" style="font-size: medium;">p</span><span class="Apple-style-span" style="font-size: medium;">.</span></span></p> <p style="margin-bottom: 0in">We have one to many relationship between dept and employee. Below is how we can translate this association in hibernate →</p> <p style="margin-bottom: 0in">@Entity</p> <p style="margin-bottom: 0in">public class Dept implements java.io.Serilizable{</p> <p style="margin-bottom: 0in"><br /></p> <p style="margin-bottom: 0in">….</p> <p style="margin-bottom: 0in">….</p> <p style="margin-bottom: 0in"> @OneToMany</p> <p style="margin-bottom: 0in"> private Collection<employee> employees;</p> <p style="margin-bottom: 0in"> public Collection<employee> getEmployees{</p> <p style="margin-bottom: 0in"> return employees;</p> <p style="margin-bottom: 0in"> }</p> <p style="margin-bottom: 0in"> public void setEmployees(Collection<employees> emps{</p> <p style="margin-bottom: 0in"> this.employees = emps;</p> <p style="margin-bottom: 0in"> }</p> <p style="margin-bottom: 0in"><br /></p> <p style="margin-bottom: 0in">}</p> <p style="margin-bottom: 0in"><br /></p> <p style="margin-bottom: 0in">Now, lets say we want to get the name of the emplyees in each dept. We will do something like →</p> <p style="margin-bottom: 0in"><br /></p> <p style="margin-bottom: 0in">Collection<dept> depts = (Collection<dept>) entityManager.createQuery(“select dept from Dept dept”).getResultSet();</p> <p style="margin-bottom: 0in">for(Dept dept:depts){</p> <p style="margin-bottom: 0in"> for(Employee emp: dept.getEmployees(){</p> <p style="margin-bottom: 0in"> //process employee</p> <p style="margin-bottom: 0in"> }</p> <p style="margin-bottom: 0in">}</p> <p style="margin-bottom: 0in">Looks simple and straightforward. But, if we have N depts, the above example will issue N+1 SQL statements to the database.</p> <p style="margin-bottom: 0in">One SQL to feth all the departments:</p> <p style="margin-bottom: 0in">select * from department;</p> <p style="margin-bottom: 0in">N SQLs to fetch emplyees for N departments.</p> <p style="margin-bottom: 0in">select * from emplyee where deptid= <id></p> <p style="margin-bottom: 0in">….</p> <p style="margin-bottom: 0in">select * from emplyee where deptid= <id></p> <p style="margin-bottom: 0in"><br /></p> <p style="margin-bottom: 0in">Now, that's a lot of calls to the DB. This is what is typically known as N+1 selection problem. There are two ways avoid this.</p> <ul> <li><p style="margin-bottom: 0in">Fetch data in batches</p> <p style="margin-bottom: 0in">You define a batch size in the relationship mapping as</p> <p style="margin-bottom: 0in">@OneToMany</p> <p style="margin-bottom: 0in">@batch-size=10</p> <p style="margin-bottom: 0in">The above will fetch employees in batches of 10 departments as →</p> <p style="margin-bottom: 0in">select *from employees deptid in (1<sup>st</sup> dept-id, ….,10<sup>th</sup> dept-id)</p> </li><li><p style="margin-bottom: 0in">Use subselect</p> </li></ul> <p style="margin-bottom: 0in"> @OneToMany</p> <ul> <p style="margin-bottom: 0in">@subselect</p> <li><p style="margin-bottom: 0in">This will issue only two SQL statements. It will use the original query (that was used to fetch the dept )as the sub query to get all employees.</p> <p style="margin-bottom: 0in">select *from employees deptid in (select id from department)</p> </li></ul> <p style="margin-bottom: 0in"><br /></p> <p style="margin-bottom: 0in">For ManyToOne and OneToOne mapping, the default fetching strategy is ESGER. Change it to LAZY if you do not want the associated object to be loaded with the main object as hibernate will issue an additional SQL to fetch the related object. If you need the related object, user EAGER-JOIN strategy so that hibernate issues one outer-join statement to retrieve two objects as opposed to two different queries. Remember to do due diligence before using EAGE-FETCH though, if hibernate fetches too many unnecessary data there is a performance overhead due to network traffic, too many objects in memory and the time hibernate takes to translate these data to objects.</p> <p style="margin-bottom: 0in">The other thing to remember is to always use the same instance of entity manager so that objects can be retrieved from the cache. Hibernate cache is maintained with the entitymanager istance. If you use different instances of entityManager, the same object will be fetched from DB repeatedly.</p> <p style="margin-bottom: 0in">Bottom line is always turn on the show-sql property to “true” in the development environment and monitor the SQL statements issued by hibernate. I can assure you from my experience that you will get great performance benefit just by optimizing the SQL calls.</p>Monika Mishrahttp://www.blogger.com/profile/06161978834743976151noreply@blogger.com2tag:blogger.com,1999:blog-7034392581493949658.post-55753611179754985562009-05-29T07:41:00.000-07:002009-05-29T07:44:23.990-07:00Testing webservice- Simplified with SoapUITesting webservice during development time can be tedious. Thanks to SoapUI, not anymore. It’s a free tool (I have not used the pro version, very happy with the free version itself) where you can create a SOAP request, send it to your webservice and see the response. The steps are very simple -><br /><ul><li>Import the <span class="blsp-spelling-error" id="SPELLING_ERROR_0">WSDL</span></li><li>Create your test suite</li><li>Drag the requests to the test suite</li><li>Enter the input values in the request (in XML format)</li><li>Execute the test case and you will see the response in the XML format</li></ul><p>During development time, I found it very convenient to use for unit testing. Once you exposed an <span class="blsp-spelling-error" id="SPELLING_ERROR_1">API</span>, export the new <span class="blsp-spelling-error" id="SPELLING_ERROR_2">WSDL</span> and test is for all possible inputs. Once you create the test cases, you can save it with the <span class="blsp-spelling-error" id="SPELLING_ERROR_3">SoapUI</span> project to use later.<br /><br />You can use <span class="blsp-spelling-error" id="SPELLING_ERROR_4">SoapUI</span> for functional testing as well by combining different requests in the same test case. You can also write your test client in Groovy script.<br /><br />I think it is a great tool for <span class="blsp-spelling-error" id="SPELLING_ERROR_5">webservice</span> developers for unit testing and recommend you to try if you have not already.</p>Monika Mishrahttp://www.blogger.com/profile/06161978834743976151noreply@blogger.com4tag:blogger.com,1999:blog-7034392581493949658.post-51825885666697562092009-05-26T14:11:00.000-07:002009-05-26T14:12:48.596-07:00Paired Programming - Two people must share the same goalThe technique is simple. Two programmers work on the same machine. One person typing the code (called driver) while the other reviewing the code (called navigator). They keep switching role as frequently as every hour.<br /><br />What are the benefits you ask?<br />Well, if more than one developer is aware of the code, the project is less dependent on any single person. Besides, the code is better as two persons have put thoughts about the implementation and reviewed each other’s work. Also, skills and knowledge is transferred between each other without any specific training sessions.<br /><br />It all sounds good theoretically, but my personal experience has been a little less cushy with implementing this technique in coding. Below is one of the main issues I found in one of the projects that I worked with.<br /><br /><strong>Paired Programming does not work if two people do not share the same goal.</strong> John and Tim were paired to code a piece of the software. During the coding, John was also assigned with another important task that only he could perform. After this, I noticed that John was assuming more of a navigator role while Tim is the driver most of the time. Also, Tim noticed a significant decrease in participation from John .He pretty much okayed whatever Tim coded. When I talked to John about it later, he told me that his mind is mostly preoccupied with the other task that he is assigned to. Since the other task is only his responsibility, he can not take any chance for that to fail. He thinks Tim can manage the coding part.<br />In the above scenario, the whole purpose of paired programming is defeated as it is as good as Tim coding the software alone. The result could be worse as the code will not be reviewed by another developer as the perception is that John has already reviewed it. We ended up in this situation because John and Tim did not share the same goal. Tim’s goal was still coding while John was more focused on the task he was assigned to.Monika Mishrahttp://www.blogger.com/profile/06161978834743976151noreply@blogger.com2tag:blogger.com,1999:blog-7034392581493949658.post-3184750786519350052009-05-19T13:09:00.000-07:002009-05-19T13:12:25.470-07:00Web Application Security & SQL-InjectionSQL Injection is a technique to inject SQL query or command as an input to the application through web pages. The intent is to make the application run some malicious SQL queries.<br /><br />Below are some of the threats from SQL Injection-><br /><br /><strong>Unauthorized Access:<br /></strong>Suppose a developer takes the username and password as inputs from the web page and executes the following query to authenticate/authorize a user.<br /><em>sqlQuery = “SELECT * from users WHERE username=’”+strUsrName+”’ AND password= ‘”+strPassword+”’”;<br /></em>If the code is determining the validity of the user by checling if any record returned from the above statement, below is a catch.<br /><br />A malicious user can pass “<em>blah’ or 1=1</em>” for password field and the code above will give the user access to the application. How? The SQL query above will now read -><br /><em>SELECT username from users WHERE username=’does nor matter’ AND<br />password= ‘blah’ OR 1=1<br /></em><br />Because of the "<em>OR 1=1</em>" condition, the query will return all the records in the users table.<br /><br /><strong>Adding a new User:<br /></strong><br />Now, in the same example pass “<em>blah’; INSERT into users (“username”,password”,”email”) values (“JohnDoe”,”hackedit”,</em><a href="mailto:johnDoe@fakeemail.com"><em>johnDoe@fakeemail.com</em></a><em>)”</em> as an input to the password field.<br />The SQL above will read -><br /><em>SELECT * from users WHERE username=’does nor matter’ AND<br />password= ‘blah’; INSERT into users (“username”,password”,”email”) values (“JohnDoe”,”hackedit”,</em><a href="mailto:johnDoe@fakeemail.com"><em>johnDoe@fakeemail.com</em></a><em>)<br /></em>The login might fail, but will create a new user account and the hacker can use it to access your application going forward.<br /><br /><strong>Changing DB Schema:</strong><br />If the DB is not read-only, we have a more serious threat. <br />Now, in the same example pass “<em>blah’; drop table users;”</em> as an input to the password field.<br />The SQL above will read -><br /><em>SELECT * from users WHERE username=’does nor matter’ AND<br />password= ‘blah’; drop table users;<br /></em>And that’s it, the user table will be dropped and nobody can access the application.<br /><strong><br />Preventing SQL-Injection:</strong><br />SQL Injection can be prevented by using parametrized SQLs.<br />The above code can be written as below and can be protected from SQL-Injection.<br /><br /><em>sqlQuery = “SELECT username from users WHERE username=? AND password= ?”<br />PreparedStatement pStmt = con.prepareStatement(sqlQuery);<br />pStmt.setString(1,strUsrName);<br />pStmt.setString(1,strPassword);<br />ResultSet rs= pStmt.executeQuery()<br /></em><br />Variables passed as arguments to PreparedStatement are escaped by JDBC drive.Monika Mishrahttp://www.blogger.com/profile/06161978834743976151noreply@blogger.com1tag:blogger.com,1999:blog-7034392581493949658.post-7422487138393539762009-05-18T11:07:00.000-07:002009-05-18T11:15:36.124-07:00iPhone 3.0 - No backward compatibilityApple declared that all the applications submitted to appstore must be complianed with iPhone3.0 OS. That means all you iPhone application needs to be upgraded.<br />New application developers, make sure your app is tested with the new OS and also works with the old OS (for people who do not switch to the new OS).Monika Mishrahttp://www.blogger.com/profile/06161978834743976151noreply@blogger.com0tag:blogger.com,1999:blog-7034392581493949658.post-28303407514780553652009-05-14T07:05:00.000-07:002009-05-14T07:09:15.709-07:00Implementing Application Security with SEAMSeam helps you secure your application without spending too much time in the details. Seam’s security model is based on a role based system. Seam leverages the Drools rule engine to support contextual, role-based permissions. The fact that we don’t have to write a single line of XML is very welcoming to developers who have used other java security framework.<br />Authentication:<br />The authentication features are built upon JAAS, but Seam offers simplified methods of authentication that hides the complexity of JAAS.<br />Steps for implementing authentication:<br />1. Switch authentication through Configuration:<br />You have to tell Seam which method handles the authentication logic. The authentication method -><br /><ul><li>Must take no argument.</li><li>Must return a Boolean indicating if credential could be verified.</li><li>Must be accessible via the EL.</li></ul><p>The authentication method can have any name and can reside in any class. The authentication routine is activated through Seam’s Identity component. You can bind the authenticating method to Identity component by adding the following line in components.xml<br /><security:identity method="#{authenticator.authenticate}"><br />The above line means the authenticate method in the authenticator component will be used for authentication.<br />2. Write an authentication method to verify user credential<br /><br /><em><span style="font-size:85%;">@Name("authenticator")<br />public class Authenticator { <br /> @In Identity identity;<br /> @In<br /> private EntityManager entityManager;<br /> public boolean authenticate() {<br /> String username = identity.getUsername();<br />String PASSWORD = identity. getPassword ();<br /> try {<br />User user = (User)entityManager.createQuery("select u from User u where u.username like :username and u.password like :password ")<br /> .setParameter("username", username)<br />.setParameter("password ", password)<br /> .getSingleResult();<br /> if(null != user.getRoles()){<br /> for(Role role: user.getRoles(){<br /> identity.addRole(role.getName());} } <br /> } catch (NoResultException ex) {<br /> log.error("Invalid username/password.", ex);<br /> return false;}<br /> return true;<br /> }<br /></span></em><br />In the above example both User and Role are application specific entity beans. The username and password in the identity component are used to find a matching User entity in DB through entityManager. Once the user is validated, the roles assigned to the user are added to the identity component. <br /><br />3. Create a login form.<br />The login form boils down to binding the username and password properties from the identity component to the username and password fields on the login form. After the properties are set, the login method in identity component is called to authenticate the user.<br />Below is an example of simple login form-><br /><br /><em><span style="font-size:85%;"><div> <h:outputLabel for="username">Username</ h:outputLabel> <h:inputText id=" username value="#{identity.username}"/> </div><br /> <div> <h:outputLabel for="password">Password</ h:outputLabel> <h:inputSecret id="password" value="#{identity.password}"/> </div><br /> <div> <h:commandButton value="Login" action="#{identity.login}"/> </div><br /></span></em><br />Authorization:<br />Authorization is about checking if a user is permitted to access a restricted resource or permitted to perform a restricted action.<br />Role based authorization:<br />Seam component are secured either in the class level or method level with @Restrict annotation.<br />Class Level Restriction:<br />Example: Restrict the component to only users with Admin role<br /><br /><em><span style="font-size:85%;">@Restrict(“#{s:hasRole(‘admin’)}”)<br />Public class AdminAction{<br /> Public void add(){<br /> }<br /> Public void delete(){<br /> }<br />}<br /></span></em><br />In the above example the user need to have admin role to perform any action under AdminAction class.<br /><br />Method Level Restriction:<br />Example: Only Super user can “delete” and Admin user can “add”.<br /><br /><em><span style="font-size:85%;">@Restrict(“#{s:hasRole(‘admin’)}”)<br />Public class AddDeleteAction{<br />@Restrict(“#{s:hasRole(‘admin)}”)<br /> Public void add(){<br /> }<br />@Restrict(“#{s:hasRole(‘super)}”)<br /> Public void delete(){<br /> }<br />}<br /></span></em><br />In the above example the user need to have admin role to perform “add” operation and super user access to perform “delete” operation.<br /><br />Note: If “Restrict” is applied both at class level and method level, method level restriction takes precedence.<br /><br />Rule based Authorization<br />Seam uses JBoss Rules to provide rule bases authorization. The advantage of rule bases authorization is a centralized location for business logics and user permissions.<br /><br />Steps for Rule based authorization:<br />1. Configure RuleBase Component in components.xml.<br /><em><span style="font-size:85%;"><component class="org.jboss.seam.drools.RuleBase" name="securityRules"><br /> <property name="ruleFiles">/META-INF/security-rules.drl</property><br /></component><br /></span></em> <br />2. Write Security rules file<br />Create a security-rules.drl in the /META-INF directory of the application’s jar file. The file should look like below-></p><p><br /><em><span style="font-size:85%;">package RuleCheck;<br />import org.jboss.seam.security.PermissionCheck;<br />import org.jboss.seam.security.Role;<br /><br />rule CanModifyRole<br />when<br /> c: PermissionCheck(name == "Role", action == "update")<br /> Role(name == "admin")<br />then<br /> c.grant()<br />end;<br /></span></em><br />The above rule states that only admin user can modify roles of other User. In the line<br />c: PermissionCheck(name == "Role", action == "update")<br />“name==’Role’” specifies the entity/component for which permission is granted and “action=’update’” specifies the specific action the user is granted access to.</p>Monika Mishrahttp://www.blogger.com/profile/06161978834743976151noreply@blogger.com3