Follow by Email

Friday, December 28, 2012

corejava: File Upload example using spring

corejava: File Upload example using spring: Below is a running example to upload a file using spring , please add the below lone in your application-context file to add CommonsMulti...

Spring Security Implement Logout Handler

In your applicationContext-security.xml file add the success-handler like below
 <logout logout-url="/resources/j_spring_security_logout" success-handler-ref="com.mycompany.security.SpringSecurityLogoutHandler" />

Create the Class which will be implemneting "org.springframework.security.web.authentication.logout.LogoutHandler" interface and in it's logout method do all the stuff you want at the time of logout.

package com.mycompany.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

public class SpringSecurityLogoutHandler implements LogoutHandler {
 @Override
 public void logout(HttpServletRequest request, HttpServletResponse arg1,
   Authentication arg2) {
  // Write your logout logic here
 }
}





Spring MVC file upload example


Below is a running example to upload a file using spring , please add the below lone in your application-context file to add CommonsMultipartResolver


   <bean id="multipartResolver"

        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

Write your JSP page like below , Please do add HTML code if you want to run it as a seprate page

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div  xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:page="urn:jsptagdir:/WEB-INF/tags/form" xmlns:table="urn:jsptagdir:/WEB-INF/tags/form/fields" version="2.0">

         <form id="fileuploadForm" action="fileupload" method="POST" enctype="multipart/form-data" class="cleanform">
          <c:if test="${successfull==Y}">
              <c:out value="File Was Successfully uploaded"></c:out>
          </c:if>
          <label for="file">File</label>
          <input id="file" type="file" name="file" />
          <p><button type="submit">Upload</button></p> 
         </form>
</div>

Write the controller to handle requests related to file upload
package com.aramco.peasd.dbp.web;

import java.io.IOException;
//import org.springframework.mvc.extensions.ajax.AjaxUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/fileupload")
public class FileUploadController {
       @ModelAttribute
       public void ajaxAttribute(WebRequest request, Model model) {

//            model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(request));

       }
       @RequestMapping(method=RequestMethod.GET)
       public void fileUploadForm() {
  

       }
@RequestMapping(method=RequestMethod.POST,produces =
"text/html"
)
       public String processUpload(@RequestParam MultipartFile file, Model model) throws IOException {
        

              model.addAttribute(  "message", "File '" + file.getOriginalFilename() + "' uploaded successfully");
              model.addAttribute("successfull", "Y");
              //**This byte array can then be sent to any content managment server  to save the file
              byte[] fileByteArray=file.getBytes();
//**Or you may want to save the file using java IO on a folder somewhere in you server             
              return "fileupload/showFileUpload";
//this will render to a page called showFileUpload.jspx
       }
       @RequestMapping(params="fileupload")
       public String showFileUploadPage(){
              return "fileupload/showFileUpload";
       }
}

 

Saturday, December 15, 2012

Deploy JPA2.0 application on weblogic10.3.3



Please note that in order to run your JPA2.0 application on weblogic10.3.3 which is JPA1.0 compliant you will have to rename your persistence.xml  to something like foo.xml and mentione the name of this xml file in your applicationContext.xml as (I am using Spring here )

   <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
        <property value="classpath:META-INF/foo.xml" name="persistenceXmlLocation"/>
        <property name="persistenceUnitName" value="persistenceUnit"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>


rename the persistenceUnit and dataSource according to the beans you have defined in your application
and you will have to define package exclusions in your weblogic.xml file as
 
 
 
<?xml version="1.0" encoding="UTF-8"?>
    <wls:weblogic-version>10.3.3</wls:weblogic-version>
 <wls:container-descriptor>
  <wls:index-directory-enabled>false</wls:index-directory-enabled>
  <!-- prefer-application-packages> <package-name>javax.persistence.spi.*</package-name>
   </prefer-application-packages -->
  <wls:prefer-application-packages>
   <wls:package-name>antlr.*</wls:package-name>
   <wls:package-name>org.apache.commons.*</wls:package-name>
   <wls:package-name>org.apache.xmlbeans.*</wls:package-name>
   <wls:package-name>org.springframework.*</wls:package-name>
   <wls:package-name>org.hibernate.*</wls:package-name>
 
   <wls:package-name>org.hibernate.validator.*</wls:package-name>
 
   <wls:package-name>javax.persistence.*</wls:package-name>
   <wls:package-name>org.joda.*</wls:package-name>
  </wls:prefer-application-packages>
 </wls:container-descriptor>
</wls:weblogic-web-app>
 

I invested few days to resolve the problem , and sharing the solution hoping it might benefit someone someday.

Below are some related threads I created for this problem , there you will find the details of problems you can face and the recomended solutions , but the solution provided above is working for me now and is gurenteed :).

https://www.coderanch.com/t/598227/Spring/Create-update-operations-ROO-causing

http://www.coderanch.com/t/599976/BEA-Weblogic/Weblogic-load-PersistenceProvider-wrong-jar

http://stackoverflow.com/questions/13806457/weblogic-10-3-3-trying-to-load-org-eclipse-persistence-jpa-persistenceprovider-i/13898999#13898999

https://forums.oracle.com/forums/thread.jspa?threadID=2474374&stqc=true

If you want to understand why we have package exclusions in our weblogic.xml file then below blog will help you alot understanding class loading in weblogic and why we need the package exclusions , I don't want to repeat the same story here , and this guy has written a great blog on it already
http://middlewaremagic.com/weblogic/?p=6725

 

Thursday, November 22, 2012

spring get bean from applicationcontext

It's very simple thanks to powerfull Spring API , You can do it as mentioned below

  
 
ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();   

 (UserCredentialsDataSourceAdapter)ctx.getBean("dataSource");
 
 

Monday, October 22, 2012

How to add Oracle JDBC driver in your Maven local repository

I found the below blog very helpfull for this information
 http://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/

Which in short guides to do following steps in order to add your JDBC driver to your Maven local repository

Run below mvn command

mvn install:install-file -Dfile=D:\app\mkyong\product\11.2.0\dbhome_1\jdbc\lib\ojdbc6.jar  -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar

of course you will have to replace the path to OJDBC jar file with your machine's path. Maven will show you a build success message. After that you will have to add following dependency to your project's pom.xml


  <!-- ORACLE database driver -->
  <dependency>
   <groupId>com.oracle</groupId>
   <artifactId>ojdbc6</artifactId>
   <version>11.2.0</version>
  </dependency>
and there you go. Oracle driver is now installed in maven repository.

  

Friday, October 19, 2012

Enabling spring security in your spring application


Enabling spring security in your spring application

In your roo application you will have to run following command which will generate all the security related pages and needed configuration for you.

Roo> Security Setup

The above command will create everything needed for spring security , now go to your “applicationContext-security.xml” file under your project’s  resources/META-INF/spring  folder.
If you want Spring to show login screen whenever your user want’s to access any URL then include following interceptors  in your applicationContext-security.xml  file under http tage

    <http auto-config="true" use-expressions="true">
        <!--
   
            <form-login />
         -->
       
<form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t" />
       
       

        <logout logout-url="/resources/j_spring_security_logout" />
        <!-- Configure these elements to secure URIs in your application -->
        <intercept-url pattern="/login**" access="permitAll" />
        <intercept-url pattern="/**" access="isAuthenticated()" />
    </http>
 
Note the  bold lines in above code , the first line will tell spring to allow access to /login URL only , while the second line will restrict all the other URLS in your application and will allow access only if the user is authenticated and has required roles.
Note that if you don’t want to have your own login page and want spring to handle security (login page based) then comment the below line
<form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t" />
       
And uncomment below line
        <!--
   
            <form-login />
         -->

Try to run your spring application now and spring will still show you a login page and notice that you don’t need to create a login.jsp page in this case.


Customizing Spring Security
We can even customize the spring security to use our own class where we can put the code to authenticate the user against our database , please follow the steps mentioned below

Writing custom AuthenticationProvider
We will write a custom Authentication provider by extending a classcalled AbstractUserDetailsAuthenticationProvider, which works with username/password like authentication. The classes that extend AbstractUserDetailsAuthenticationProvider have to provide implementation for its two abstract methods:
·         additionalAuthenticationChecks and
·          retrieveUser.
The provider calls the retrieveUser method to authenticate user , this is where you can authenticate the user in your application against your own database , below is the class

package mypackage;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

public class DrillingBestPracticesAuthenticationProvider extends
              AbstractUserDetailsAuthenticationProvider {

       @Override
       protected void additionalAuthenticationChecks(UserDetails arg0,
                     UsernamePasswordAuthenticationToken arg1)
                     throws AuthenticationException {
              // TODO Auto-generated method stub

       }

       @Override
       protected UserDetails retrieveUser(String username,
                     UsernamePasswordAuthenticationToken authentication)
                     throws AuthenticationException {
              String password = (String) authentication.getCredentials();
              if (!StringUtils.hasText(password))
              {
                     throw new BadCredentialsException("Please enter password");
             
              }
              List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
              try
              {
                    
                     //TODO here I should be trying to get the database connection using user name and password if connection successfully made then it means user is authenticated to use our system
                    
                    
              }
              catch (EmptyResultDataAccessException e)
              {
                     throw new BadCredentialsException("Invalid username or password");
                    
              } catch (EntityNotFoundException e) {
                     throw new BadCredentialsException("Invalid user");
                    
              } catch (NonUniqueResultException e) {
                     throw new BadCredentialsException("Non-unique user, contact administrator");
                    
              }
              return new User(username, password,
                           true, // enabled
                           true, // account not expired
                           true, // credentials not expired
                           true, // account not locked
                           authorities);       
       }

}

And you will have to add AuthenticationManager in your applicationContext-security.xml file as below


<beans:bean name="drillingBestPracticesAuthenticationProvider" class="mypackage.DrillingBestPracticesAuthenticationProvider">
    
    </beans:bean>
    <authentication-manager alias="authenticationManager">
    <authentication-provider ref="drillingBestPracticesAuthenticationProvider"></authentication-provider>
    </authentication-manager>    


Now once the user has been authenticated and User object being returned by the retrieveUser method , Spring will allow you to get user detail from anywhere in your application using any of the three approaches mentioned in the blogpost at following link
I am copy pasting the three methods mentioned in above blog
 three ways to get current logged in username in Spring Security

First Method
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      String name = auth.getName(); //get logged in username
Second Method
     User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      String name = user.getUsername(); //get logged in username
Third Method
  @RequestMapping(value="/login", method = RequestMethod.GET)
  public String printWelcome(ModelMap model, Principal principal ) {
 
      String name = principal.getName(); //get logged in username
      model.addAttribute("username", name);
      return "hello";
 
  }

Saturday, October 13, 2012

Weblogic BEA-149265 , Caused By: java.lang.ClassNotFoundException: HttpServlet


Problem Description
I am using weblogic 10.3.3 server and was trying to deploy a web based application (build in eclipse).

 I have configured weblogic 10.3.3 server in eclipse and the application had no errors. It was running from inside eclipse like a charm.
After finishing the development and to test the application outside eclipse environment, I started standalone server instance (weblogic 10.3.3 outside eclipse , from command prompt) and was trying to deploy the same application and saw this strange error

<Error> <Deployer> <BEA-149265> <Failure occurredin the execution of deployment request with ID '1350125256034' for task '6'. Error is: 'weblogic.management.DeploymentException: 'weblogic.management.DeploymentException:        at weblogic.application.internal.BaseDeployment.throwAppException(BaseDe
ployment.java:157)

Caused By: java.lang.ClassNotFoundException: HttpServlet
        at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(Generic
ClassLoader.java:280)
        at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClass
Loader.java:253)
        at weblogic.utils.classloaders.ChangeAwareClassLoader.findClass(ChangeAw
areClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
        Truncated. see log file for complete stacktrace
> 

I was surprised to see it because same machine same server instance , if I run it from eclipse it works fine , outside eclipse it doesn’t work.
As you can see from the error message it was having problem loading the HTTPServlet  while deploying the application.
But the thing which wasted a lot of time was why the hell it is working on eclipse , as I was using the same weblogic server.
Ideally the servlet jar file shouldn’t be in your webapp/lib directory and it wasn’t , server will have it’s own copy of the jar file in it’s class loader.
Solution
It took some time to find the solution but it’s easy. I used eclipse to export a war file of my web project, and then started weblogic and deployed the war file instead of web app folder and it’s working now.
Similar problem encountered at test server
I saw the same problem on test even with the war file , after trying everything we can do to get rid of this problem with no success we decided to restart the Test instance.
The application was deployed successfully after Server restart.

Infect this solution should be followed as a practice
 When you export war file eclipse takes care of all the dependent jars and puts them in your war file , so if there is any possibility that you are using an external  library in your application eclipse will take care of including it in the final war when you export the project as a war file.
It is therefore highly recommended to export your eclipse project as WAR file and then send it for deployment.  

Tuesday, September 11, 2012

Spring MVC from getting started to advance level

Below are some very good resources for getting started in Spring MVC

A very good introductory article of Spring MVC

http://blog.springsource.com/2011/01/04/green-beans-getting-started-with-spring-mvc/

Spring showcase
 http://blog.springsource.org/2010/07/22/spring-mvc-3-showcase/



Thursday, August 30, 2012

Common mistakes done in applications which can give a hacker full knowledge of your database

Its a bad practice to throw the whole exception message on the client console , if the exception is a jdbc exception throwed because of an error in update,  any error in trigger execution e.t.c the raw exception stack trace has a lot of information about the tables in database fields in it and business rules implenented which caused this exception. This is a lot for a hacker he can easily build a knowledge base based on these exceptions,  validations and business rules implemented in your database,  infact your whole database can be open to him.
Its therefor a bad practice to let the presentation layer see the raw jdbc exception stack trace instead application developers should try to develop the wrapper exceptions and should try to show only relevent exception data on presentation layer.

Note : "I recently had a chance to work with a very good consultant from Mcafee, he told me that this is one of the main reasons hackers can hack the most secured applications easily once they hv access to the application they try different operations to cause the exceptions and build their knowledge by looking into the different exception". This was a very good informative session where I learnt a lot I will be writing more blogs on it so keep your fingers crossed and wait for some more good blog posts: ).

Saturday, August 4, 2012

java.sql.SQLSyntaxErrorException: ORA-01722: invalid number

One possible reason for java.sql.SQLSyntaxErrorException: ORA-01722: invalid number and it's solution



I encountered this exception today and the cause of it was very obvious and eventually I learned a very good practice out of it

Below is the query I was trying to execute

select * from a_table where bi_num= 60

Surprisingly this query was showing me some results in PL\ SQL developer initially but when I tried to fetch the complete result set it gave me this "ORA-01722: invalid number" exception.

Reason :


As you can see the name of the field "bi_num" gave me a feeling that it is a number field in oracle that is why I had the numeric comparison in query , but bi_num was eventually declared as varchar field in the database and in some records it had values which could have been converted to number the other records had no numeric values. When oracle was trying to fetch the data according to condition in query, because of comparison with a number oracle was trying to convert values in bi_num to number.
For few records it worked but the records having string values of course oracle couldn't convert those to number and gave me "ORA-01722: invalid number" exception.

Solution:


After understanding the problem solution was very simple , I changed the query to have a string comparison like below

select * from a_table where bi_num= '60'

So now oracle will always do the string comparison and will not convert values to numbers.

I hope this will help someone out there :).

Thursday, July 26, 2012

HTML Give border title in div

In HTML to have a table with title in it's border like we can have in swing , we can use div element like shown in below code snipet

<div  style="width:100%;">
    <fieldset>
    <legend style="color:blue;font-weight:bold;">Initiator Information</legend>


      <table  border="0" cellpadding="0" cellspacing="5" >
        <tr>
          <td width="146">User Id</td>
          <td width="216"><label for="userId"></label>
            <input type="text" name="userId" id="userId" /></td>
          <td width="122">Name</td>
          <td width="474"><input type="text" name="userName" id="userName" /></td>
        </tr>
        <tr>
          <td>Department</td>
          <td><label for="userDepartment"></label>
            <input type="text" name="userDepartment" id="userDepartment" /></td>
          <td>Division</td>
          <td><label for="userDevision"></label>
            <input type="text" name="userDevision" id="userDevision" /></td>
        </tr>
      </table>
     
    </fieldset>
    </div>


The above code will show the div in browser like below