Tuna Töre

JQuery ajax file upload example


<script type="text/javascript">

	function ajaxFileUpload(load)
	{
		var photo = '<c:out value="${user.photopath}"/>';
		var id= '<c:out value="${user.idUser}"/>';
		
		if(load == false) {
			if(photo == 'null' | photo == '') {	
				$("#rePhoto1").attr("src", "/kameroom/display/images/main/logo.png"); 
				return false;
			}
			var sr = "<%=request.getContextPath()%>/uploads/thumbnail/profile/"+ id + "/"+ photo;
			$("#rePhoto1").attr("src", sr); 
			return false;
		}
		
		var fileType = $('#photo').val().split('.').pop().toLowerCase();
		
		if(fileType == '') {
			alert('Please select a photo first');
			return false;
		}
		if($.inArray(fileType, ['bmp','png','jpg','jpeg']) == -1) {
		    alert('Invalid file type, only bmp, jpg and png supported');
		    return false;
		}

		var s = '';
		$.ajaxFileUpload
		(
			{
				url:'<%=request.getContextPath()%>/profile/photoupload.k',
				secureuri:false,
				fileElementId:'photo',
				dataType: "xml",
				success: function (xml, status)
				{
					
					$(xml).find("p").each(function() {
						 s = "/kameroom" + $(this).find("l").text();
					});
					
                    var img = $("<img style=\"width: 100px!important;border: 0!important;height: auto!important;\" onclick=\"return false;\"/>").attr("src", s + "?" + new Date().getTime())
					.load(function() {
                    	$("#rePhotoMain").html('');
                     	$("#rePhotoMain").append(img);               
                    });

					if(typeof(xml.error) != 'undefined')
					{
						if(xml.error != '')
						{
							alert(xml.error);
						}else
						{
							alert(xml.msg);
						}
					}
				},
				error: function (xml, status, e)
				{
					alert('contact@kameroom.nl ' + e);
				}
			}
		);
		
		return false;

	}
	
	</script>

14/05/2015 Posted by | jQuery | Leave a comment

Spring MultipartFile file upload example


package nl.kameroom.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.coobird.thumbnailator.Thumbnails;
import nl.kameroom.image.ImageService;
import nl.kameroom.user.UserManager;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import sun.java2d.pipe.BufferedBufImgOps;

@Controller
public class FileUploadController {

	@Value("#{settings['upload.profile.thumb.loc']}")  
	private String profileThumbPath= "";
	 
	@Value("#{settings['upload.profile.org.loc']}")  
	private String profileOrgPath= "";
	
	@Value("#{settings['upload.advert.thumb.loc']}")  
	private String advertThumbPath= "";
	
	@Value("#{settings['upload.advert.org.loc']}")  
	private String advertOrgPath= "";

	private UserManager userManager;
	private ImageService imageService;

	@Autowired
	public void setUserManager(UserManager um) {
		userManager = um;
	}
	
	@Autowired
	public void setImageService(ImageService is) {
		imageService = is;
	}

    @RequestMapping(value = "/profile/photoupload.k", method = RequestMethod.POST)
    public @ResponseBody ResponseEntity<String> profilePhotoUpload(@RequestParam("photo") MultipartFile file,
    		ModelMap model, 
    		HttpServletRequest request, 
    		HttpServletResponse response,
    		Authentication auth) {
    	
    	String orgName = "";
    	String r = "";
    	int idUser = 0;
        if (!file.isEmpty()) {
          try {
    	   	
    	    byte[] bytes = file.getBytes();					
            orgName = "p" + "." + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".")+1);
            r = imageService.validateFile(file.getContentType(),file.getName(), file.getOriginalFilename(), file.getSize());
            if(r.equals("")) {

            idUser = userManager.getUserIDByUsername(auth.getName());
            File dest = new File(profileOrgPath + idUser + "/");
            File destFile = new File(profileOrgPath + idUser + "/" + orgName);
            
            if(!dest.exists()) {
            	dest.mkdir();             	
            } else {
            	//remove all files
            	File[] inDir = dest.listFiles();
            	for (int i = 0; i < inDir.length; i++) {
					inDir[i].delete();					
				}
            }
            
            BufferedImage img = ImageIO.read(file.getInputStream());
            //file.transferTo(destFile);   
            imageService.compressAndWriteImage(img, destFile);
            
            //profile thumb photo            
            File outFile = new File(profileThumbPath + idUser +"/");
            if(!outFile.exists()) {
            	outFile.mkdir(); 
            }
            else
            {	//remove all files
            	File[] inDir = outFile.listFiles();
            	for (int i = 0; i < inDir.length; i++) {
					inDir[i].delete();					
				}
            }
            
            Thumbnails.of(img).forceSize(112, 81).toFile(outFile + "/" + orgName);
            //profile thumb photo
            userManager.setUserProfilePath(idUser, orgName);
			} 
            } catch (Exception e) {
            	//LOGGING
                e.printStackTrace();
            }
            
            String json= "";
          	if(r.equals(""))
          		json = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><p><n>"+orgName+"</n><l>/uploads/thumbnail/profile/"+ idUser + "/" + orgName+"</l></p>";
          	else
          		json = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><p><e>" + r + "</e></p>";
          	HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentType(MediaType.TEXT_XML);
            return new ResponseEntity<String>(json, responseHeaders, HttpStatus.OK);

       } else {
    	   return  null;
       }      
    }

}

14/05/2015 Posted by | Spring Framework | Leave a comment

Spring @Value example


@Value("#{settings['upload.advert.thumb.loc']}")  
private String advertThumbPath= "";

@Value("#{settings['upload.advert.org.loc']}")  
private String advertOrgPath= "";

14/05/2015 Posted by | Spring Framework | Leave a comment

Spring auto login controller GrantedAuthority


package nl.kameroom.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class AutoLoginController {


	@RequestMapping({ "/navigate.k" })
	public ModelAndView navigate(@RequestParam("email") final String email, 
			@RequestParam("k") String key, 
			HttpServletRequest request,
			HttpServletResponse response, Authentication auth) throws Exception { 			

		String nav= "index";
		
		if(auth== null) {
			//Spring Security Auto Login
			try {
				String keyinDB = userManager.getReminderUserPassKey(email);
				if(keyinDB.equals(key)) { 
					GrantedAuthority ga = new GrantedAuthorityImpl("USER");			
					List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
					authorities.add(ga);			
					AbstractAuthenticationToken token = new UsernamePasswordAuthenticationToken(email, "", authorities);
					SecurityContextHolder.getContext().setAuthentication(token);
					
				}else {
					nav = "login/login";					
				}			
			} catch (Exception e) {
				SecurityContextHolder.getContext().setAuthentication(null);
				
			}
		}
		
		return new ModelAndView(nav);
	}
}


14/05/2015 Posted by | Spring Framework | Leave a comment

Spring ResponseBody List with JQuery autocomplete


//city list
$("input#location").autocomplete({
width: 300,
max: 10,
delay: 0,
minLength: 1,
autoFocus: false,
cacheLength: 1,
scroll: true,
highlight: false,
source: function(request, response) {
$.ajax({
type : "POST",
url: "<%=request.getContextPath()%>/cityList.k",
dataType: "json",
data: "cityName=" + $("input#location").val(),
success: function( data, textStatus, jqXHR) {
$("#nav").val('c');
$("#validated").val('0');
//console.log( data.idCity);
var items = data;
//jQuery.each(data, function(i, val) {
//response(val.idCity);
//});
response(items);
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error contact@kameroom.nl");
}
});
}, close: function (event, ui) {
//alert('close' +this.value);
//alert('selected');
return false;
},
select: function (event, ui) {
$("input#location").val(ui.item.cityName);
$("input#idCity").val(ui.item.idCity);
$("#cityError").hide();
$("#validated").val('1');
//alert('selected');
return false;
},
focus: function(event, ui) {
//$("input#place").val(ui.item.cityName);
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.cityName + "</a>")
.appendTo(ul);
};
@RequestMapping(value="/cityList.k", method=RequestMethod.POST)
public @ResponseBody List<City> cityList(
@RequestParam("cityName") String cityName,
ModelMap model, HttpServletRequest request) throws Exception {
List<City> cityList = locationManager.cityList(cityName);
return cityList;
}

14/05/2015 Posted by | Spring Framework | Leave a comment

Spring RequestMapping with ConstraintViolation


package nl.kameroom.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import nl.kameroom.contactservice.ContactInfo;
import nl.kameroom.contactservice.ContactService;
import nl.kameroom.util.LocaleMessageSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.ResponseBody;
@Controller
public class ContactController {

private ContactService contactService;
private LocaleMessageSource messageSource;
private Validator validator;

@Autowired
public void setLoginService(ContactService cs) {
contactService = cs;
}

@Autowired
public void setValidator(Validator v) {
validator = v;
}

@Autowired
public void setLocaleMessageSource(LocaleMessageSource ms) {
messageSource = ms;
}

@SuppressWarnings("rawtypes")
@RequestMapping(value="/contactInfoAJAX.k", method=RequestMethod.POST)
public @ResponseBody String[] sendForm(
@RequestParam("subject") String subject,
@RequestParam("content") String content,
@RequestParam("email") String email,
@RequestParam("category") String category,
@RequestParam("mq") String mq, ModelMap model, HttpServletRequest request) throws Exception {

ContactInfo ci = new ContactInfo();
ci.setContent(content);
ci.setFrom(email);
ci.setSubject(subject);
ci.setCategory(Integer.valueOf(category));

Set<ConstraintViolation<ContactInfo>> constraintViolations = validator.validate(ci);

String[] messages = new String[constraintViolations.size()];
ArrayList<String> mList = new ArrayList<String>();

for (int i = 0; i < constraintViolations.toArray().length; i++) {
ConstraintViolation constraintViolation = (ConstraintViolation)constraintViolations.toArray()[i];
mList.add(constraintViolation.getMessage());
}
Collections.sort(mList);
for (int i = 0; i < mList.size(); i++) {
messages[i] = messageSource.getMessage(mList.get(i).substring(1), request);
}

//validation error occurred
if(messages.length > 0) {
return messages;
}

boolean r = contactService.insertContactInfo(ci);
if(r==true)
return new String [] {};
else
return new String [] {"srvError"};
}
}

14/05/2015 Posted by | Spring Framework | Leave a comment

JQuery form trigger and action



<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ include file="/WEB-INF/pages/component/meta.jsp" %>
<%@ include file="/WEB-INF/pages/component/datatable.jsp" %>
<link rel="stylesheet" type="text/css" media="screen" href="<%=request.getContextPath()%>/display/accordion/style.css" />
<title><spring:message code="roomwanted.title" text="Advertise room wanted"/></title>
<script type="text/javascript">

function doPost(advType){
if(advType == 'room')
$('#srch').attr('action', '<%=request.getContextPath()%>/searchroom.k');
else if (advType == 'tenant')
$('#srch').attr('action', '<%=request.getContextPath()%>/searchtenant.k');
$("#srch").trigger("submit");
}
</script>
</head>
<body>

<div class="wrapper">

<%@ include file="/WEB-INF/pages/component/sidebar.jsp"%>

<div id="pageContent">


<div class="wikistyle">

<div id="sitetext">
<h1>
<a href="<%=request.getContextPath()%>" style="text-decoration: none">kameroom.nl</a>
</h1>
</div>

<div class="menu">
<%@ include file="/WEB-INF/pages/component/dropdown.jsp"%>
</div>

<div id="welcometext">
<h2 style="padding: 0 !important;"></h2>
</div>

<div id="container">
<div id="wrap">
<div id="main">
<pre class="noteyellow"><spring:message code="advert.free" text="Finding a new room or tenant here is easy and fast"/></pre>
<br/>
<form name="srchForm" id="srch" method="post">
<ul id="stepForm">
<li id="sf1">
<div>
<fieldset>
<h3 class="stepHeader">Find the room you want easily</h3>
<div class="buttonWrapper">
<center>
<input name="formNext1" type="button" class="open1 nextbutton3" value="Search a new room" onclick="doPost('room')"/>
</center>
</div>
</fieldset>
</div>
</li>
<li id="sf1">
<div>
<fieldset>
<h3 class="stepHeader">Find a new tenant for your room</h3>
<div class="buttonWrapper">
<center>
<input name="formNext1" type="button" class="open1 nextbutton3" value="Search a new tenant" onclick="doPost('tenant')"/>
</center>
</div>
</fieldset>
</div>
</li>
</ul>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

14/05/2015 Posted by | jQuery | 1 Comment

Spring AuthenticationSuccessHandler


package nl.kameroom.security;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.kameroom.user.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

public class AuthenticationHandler implements AuthenticationSuccessHandler{

 private UserManager userManager = null;

 @Autowired
 public void setLoginService(UserManager um) {
 userManager = um;
 }

 @Override
 public void onAuthenticationSuccess(HttpServletRequest request,
 HttpServletResponse response, Authentication authentication) throws IOException,
 ServletException {
 userManager.updateLastLogin(((User)authentication.getPrincipal()).getUsername());
 response.sendRedirect("/kameroom/profile/profile.k");

 }
}

14/05/2015 Posted by | Spring Framework | Leave a comment

JsonProperty example


package nl.kameroom.searchservice;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonProperty;

/**
 * The data tables response.
 */
@SuppressWarnings("serial")
public class DataTablesResponse <T> implements Serializable {
 
 @JsonProperty(value = "sEcho")
 public int echo;
 @JsonProperty(value = "iTotalRecords")
 public int totalRecords;
 @JsonProperty(value = "iTotalDisplayRecords")
 public int totalDisplayRecords;
 @SuppressWarnings("unused")
 @JsonProperty(value = "messages")
 private String[] messages;
 @JsonProperty(value = "aaData")
 public List<T> aaData = new ArrayList<T>();

 public void setMessages(String[] messages) {
 this.messages = messages;
 }
 
}

14/05/2015 Posted by | JSON | Leave a comment

Spring QuartzJobBean example


package nl.kameroom.emailservice;

import java.util.HashMap;
import java.util.Map;

import nl.kameroom.advert.AdvertManager;
import nl.kameroom.advert.AdvertPublished;
import nl.kameroom.user.UserManager;
import nl.kameroom.util.LocaleMessageSource;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class AdvertPublishedJob extends QuartzJobBean {

 private LocaleMessageSource localeMessageSource;
 private AdvertManager advertManager;
 private EmailService emailService;
 private UserManager userManager;
 
 public void setAdvertManager(AdvertManager am) {
 advertManager = am;
 }
 
 public void setLocaleMessageSource(LocaleMessageSource ms) {
 localeMessageSource = ms;
 }
 
 public void setEmailService(EmailService es) {
 emailService = es;
 }
 
 public void setUserManager(UserManager um) {
 userManager = um;
 }
 
 @Override
 protected void executeInternal(JobExecutionContext arg0)
 throws JobExecutionException {
 
 //ROOM ADVERTS
 for (AdvertPublished advertRoomPublished : advertManager.getRoomAdvertsPublished()) {
 sendRoomNotification(advertRoomPublished);
 advertManager.updateEmailSentAndTime(Integer.valueOf(advertRoomPublished.getIdadvert()));
 }
 
 //ROOM WANTED ADVERTS
 for (AdvertPublished advertRoomWantedPublished: advertManager.getRoomWantedAdvertPublished()) {
 sendRoomWantedNotification(advertRoomWantedPublished);
 advertManager.updateEmailSentAndTime(Integer.valueOf(advertRoomWantedPublished.getIdadvert()));
 }
 
 
 }

 public void sendRoomNotification (AdvertPublished apub) {
 
 Map<String, Object> model1 = new HashMap<String, Object>();
 model1.put("from", "norepy@kameroom.nl"); 
 model1.put("subject", "Room Advert published @kameroom.nl " + apub.getStreetname()); //CHANGE
 model1.put("to", apub.getEmail()); //Attention 
 model1.put("place", apub.getCityname()); 
 model1.put("postcode", apub.getPostcode()); 
 model1.put("street", apub.getStreetname()); 
 model1.put("housenum", apub.getHousenum()); 
 model1.put("rent", apub.getRent()); 
 model1.put("id", apub.getIdadvert());
 model1.put("name", apub.getName());
 model1.put("nurl", "http://www.kameroom.nl/navigate.k?email="+apub.getEmail()+"&k="+userManager.getReminderUserPassKey(apub.getEmail())+"&p=viewradvert&id="+apub.getIdadvert()+"&language="+apub.getLanguage());
 boolean result = false;
 if(apub.getLanguage().equals("EN")) {
 result = emailService.send("roompublished.vm", model1); } 
 else {
 result = emailService.send("roompublished_nl.vm", model1); 
 }
 if(result == true)
 {
 //logging
 } 
 
 }
 public void sendRoomWantedNotification (AdvertPublished apub) {
 
 Map<String, Object> model1 = new HashMap<String, Object>();
 model1.put("from", "noreply@kameroom.nl"); 
 model1.put("subject", "Room Wanted Advert published @kameroom.nl " + apub.getCityname()); //CHANGE
 model1.put("to", apub.getEmail()); //Attention 
 model1.put("place", apub.getCityname()); 
 model1.put("name", apub.getName());
 model1.put("id", apub.getIdadvert());
 model1.put("minrent", apub.getMinrent());
 if(apub.getMinrent().equals(apub.getMaxrent()))
 model1.put("maxrent", "2000+");
 else
 model1.put("maxrent", apub.getMaxrent());
 model1.put("nurl", "http://www.kameroom.nl/navigate.k?email="+apub.getEmail()+"&k="+userManager.getReminderUserPassKey(apub.getEmail())+"&p=viewrwadvert&id="+apub.getIdadvert()+"&language="+apub.getLanguage());
 boolean result = false;
 if(apub.getLanguage().equals("EN")) {
 result = emailService.send("roomwantedpublished.vm", model1); } 
 else {
 result = emailService.send("roomwantedpublished_nl.vm", model1); 
 }
 if(result == true){
 //logging
 } 
 
 }
}

14/05/2015 Posted by | Spring Framework | Leave a comment

Follow

Get every new post delivered to your Inbox.