Monday 29 July 2013

Fetch Image From Data Base In JAVA Spring

Fetch Image from data base in Java or Spring 

<img alt="User Image" id="UserImage" src="/person/getPhoto?id=${client.id}" width="150" height="150" >

In above image tag the marked data will call the controller method with ID of Person whose image you want to get



@RequestMapping(method = RequestMethod.GET, value = "getPhoto")
public void getPhoto(HttpServletRequest request,
HttpServletResponse response) throws FileUploadException,
IOException {
int id = 0;
Person pi = null;
 id = Integer.parseInt(request.getParameter(ID));
pi = PersonService.getCaregiver(id).getPerson();   //get photo form db
response.setContentType("image/jpg");
response.getOutputStream().write(pi.getPhoto());
response.getOutputStream().flush();
response.getOutputStream().close();
}




Wednesday 24 July 2013

combo-box(Drop down) Change event populate or fetch value from table using ajax in liferay

Hi Friends ,

Today i want to share small ajax portlet example with you . As every post i explain step by step..

I have one combo box & when user change value so according that onchange event i fetch value from db using ajax.


As In above image when user select birthday category then in fetch keyword from db table & append multi select .

Now time for code :

First In Jsp File write below code:

<portlet:resourceURL var="fetchValues" id="fetchcombo"></portlet:resourceURL>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>

<script>
$(document).ready(function() {
       $("#category").change(function() {
var keyId=$("#category").val();
document.getElementById("Features").innerHTML="";

                       var url = "<%=fetchValues%>";
           $.post(url, {keyId : keyId}, function(data)  {
               

Add Captcha in custom portlet with refresh using ajax

Hi Friend,

Here i want to explain how to add captch image in custom portlet & refresh that captch .So i explain step by step.



First in Jsp File Write below code .

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
jQuery("#refreshCaptchaActivity").click(function()
{

jQuery(".captcha").attr("src", jQuery(".captcha").attr("src")+"&force=" + new Date().getMilliseconds());
return false;
});
</script>

<div>
<portlet:resourceURL var="captchaURL" />
<liferay-ui:captcha url="<%=captchaURL%>" />
<div style="padding: 23px 0 0 5px; cursor: pointer;">
<img id="refreshCaptchaActivity"
src="<%= request.getContextPath()%>/refresh.png">
</div>
</div>

//here serveResource Method is used forhandle ajax call in jrs 286 portlet....
Now in java classs we implement serveResourse as well as validate the captch which user enter is valide or not..

Sunday 7 July 2013

How to update and delete data in database using search container in liferay?

Hi Liferay members , in my previous post i have explained to retrieve data from database this time i am going to show you how to update those data from database .
Just follow this simple steps

list.jsp 

1)Open list.jsp where you have written code for search container to retrieve data and this following line in that container.

<liferay-ui:search-container-column-jsp path="/button.jsp" />

button.jsp

1)Now create button.jsp and add following snippet of code


<%ResultRow rslt=(ResultRow)request.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW) ;

Foo f=(Foo)rslt.getObject();

String prk=String.valueOf(f.getFooId());

%>
//Button menu tag
<liferay-ui:icon-menu>

//Create “editProduct” method in Action file
<portlet:actionURL var="editURL" name="editProducts">
<portlet:param name="edit" value="<%=prk %>"/>
</portlet:actionURL>

// ”EDIT” button for Update event. 
<liferay-ui:icon image="edit" message="Edit" url="<%=editURL.toString() %>"/>
</liferay-ui:icon-menu>

//Creates "deleteproducts" method in action file
<portlet:actionURL var="deleteURL" name="deleteproducts">
<portlet:param name="edit" value="<%=prk %>"/>
</portlet:actionURL>
<liferay-ui:icon-delete url="<%=deleteURL.toString() %>" />


Saturday 6 July 2013

Ajax in Spring mvc Example Spring 3 MVC JSON Example

Ajax in Spring

Make a JSON Call On Any event of the html element to fetch the data from database

Ex:

<input type="button" Value="Call addMyData" onclick="addMyData()"  />

here we are defining a function  addMyData() which we have called on button click event.
 

function addMyData()
{
var name="Hello";
var address="Ahmedabad";
$.ajax({
type : "POST",
dataType : "json",
url :"/hello/addData",    //   This is RequestMapping Value of controller
                          //   if you are working in spring you can also write 
                          //   URL  like url: realativePath/adaData  or
                          //   url: realativePath/addData.do  etc
data : {
        name:name,
        address:address
        },
success : function(response) {
console.log(response);    //  This is response from the server After the                                       success of ajax call
},
error:function(s,st){                      // This will be executed if ajax call is failed  or return with error  ////
alert("error"+s);
}
}).done(function() {
alert("Call is Completed");           // This will execute when ajax call complete
});
}

IN CONTROLLER

you just need to return json data if u want to return any data 


just create a json object


JSONObject json=new JSONObject()


append some data to it

json.put("addedName",name)  // where name is your        variable in controller 
and send this in to response


response.getWriter().write(json.toString());
Now if u want to get this data in json call success


success:function(response){
alert(response.addedName);
}



IF any query ask me, i will back to you as fast as posible thanks for visiting this blog




Tuesday 2 July 2013

Upload Image With AJAX In Spring MVC

Here i have uploaded image to database using spring mvc and hibernate.

you need to create Photo column in Model.

Modal

@Entity
@Table(name="person_information")
public class Person implements Serializable {

@Column(name="Photo")
@Lob
private byte[] photo; 

public byte[] getPhoto() {
        return photo;
    }

public void setPhoto(byte[] photo) {
        this.photo = photo;
    }

Ajax Function Call On any Html Element

call ajax function on click event of upload button.

<input type="button" Value="Upload" onclick="performAjaxSubmit()" />
function performAjaxSubmit() {
var id = $("#pid").val();
var photoFile= document.getElementById("photo").files[0];
var formdata = new FormData();
formdata.append("sampleFile", photoFile);
formdata.append("id", id);
var xhr = new XMLHttpRequest();
xhr.open("POST", url + "/person/UploadPhoto", true);
xhr.send(formdata);
xhr.onload = function(e) {
if (this.status == 200) {
             alert("Photo Successfully uploaded")
}
};
}

Controller Mehtod for Upload

this method is in class and this class is having @RequestMapping('/client/')
u need to include some dependancies in pom file because i have used image scaler  plugins   

@RequestMapping(method = RequestMethod.POST, value = "UploadPhoto")
public void uploadPersonPhoto(HttpServletRequest request,
HttpServletResponse response)                                                                                                              throws FileUploadException,IOException
{
File uploadedFile = null;
String ajaxUpdateResult = "";
int id = 0;
String fileName = "";
Person p = null;
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
 for (FileItem item1 : items) //for starts
 {
if (item1.isFormField())
     {
id = Integer.parseInt(item1.getString());
p = personService.getPersonInformation(id);
 
      } else
     {
Iterator iterator = items.iterator();
 
       while (iterator.hasNext())  //while starts
       {
FileItem item = (FileItem) iterator.next();
              if (!item.isFormField())
              {
fileName = item.getName();
String root = "src/main/webapp/resources/upload/";
File path = new File(root + "/fileuploads");
 
if (!path.exists()) {
path.mkdirs();
}
uploadedFile = new File(path + "/" + fileName);
 
             try {
item.write(uploadedFile);                   ////The File Willbe Uploaded at above given path                                                                                          /////       src/main/webpage/resources/upload/
} catch (Exception e) {
}
ajaxUpdateResult = fileName + " is Uploaded Successfully" ;
}
}  //while End
} 
} //for loop end
 BufferedImage bi = new BufferedImage(150, 150,BufferedImage.TYPE_BYTE_BINARY);
 
bi = ImageIO.read(uploadedFile);
BufferedImage bio = Scalr.resize(bi, 150);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bio, "jpg", baos);
byte[] bFile = baos.toByteArray();

          p.setPhoto(bFile);      ///////this will upload file in database in byte format
 
          response.getWriter().print(ajaxUpdateResult);
}

Retrieve Data From Database Using Liferay Search Container in Aui Tab

Hi Liferay members in my last post i have shown to retrieve data from database but this time i am going to show data in liferay search container using aui tab.
Follow this steps.


AUI Tab in View.jsp

1)Write the following Script in your Jsp page
<script type="text/javascript">
AUI().ready(
'aui-tabs', 'substitute',
   function(A) {
       var tabs1 = new A.TabView(
           {
               boundingBox: '#markupTabs',
               listNode: '#test',
               contentNode: '#testContent'
           }
       );
       tabs1.render();        
   }
);
</script>

get custom field (expando table) value in velocity template

Hi all ,

First accessing service of liferay in velocity we have to enable serviceLocator.
You have to right below line to enable to servicLocator in portal-ext.properties file & restart server.

where to find portal-ext.properties click here.

journal.template.velocity.restricted.variables=


Now in template right below code to get particular user field value..

how to create Responsive theme in liferay ?

Hi Friend ,

Step By Step I will Explain to create responsive theme in liferay.

  create New liferay Project In eclipse.click on liferay IDE Icon & select  "New Lifray Project".

 Then select Give Project name & at last select "Theme" option.

Now You get below package structure .