Skip to content

Commit

Permalink
Android development
Browse files Browse the repository at this point in the history
  • Loading branch information
brunano21 committed May 24, 2014
1 parent c5668fd commit b03a5e1
Show file tree
Hide file tree
Showing 8 changed files with 314 additions and 37 deletions.
5 changes: 5 additions & 0 deletions .classpath
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,10 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
4 changes: 2 additions & 2 deletions .settings/org.eclipse.wst.common.component
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-modules id="moduleCoreId" project-version="1.5.0">
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="JensProject">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<property name="java-output-path" value="/JensProject/target/classes"/>
<property name="context-root" value="supermarket"/>
</wb-module>
Expand Down
31 changes: 31 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.mobile</groupId>
<artifactId>spring-mobile-device</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>


<!-- CGLib for @Configuration -->
Expand Down Expand Up @@ -148,6 +154,31 @@
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-remote-shell</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
</dependencies>

<repositories>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package ai.server.controller;

import hibernate.Utente;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import dati.Dati;

@Component
public class AndroidAuthenticationProvider implements AuthenticationProvider {

@Autowired
private Dati dati;

public void setDati(Dati dati){
this.dati = dati;
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();

System.out.println(username);
System.out.println(password);

Utente utente = dati.getUtenti().get(username);
if(utente != null) {
if(!utente.getConfermato() || !utente.getPassword().equals(password))
utente = null;
} else {
System.out.println("User " + username + " not found");
return null;
}

final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(username, password, grantedAuths);
final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
return auth;

}

@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}

}
94 changes: 93 additions & 1 deletion src/main/java/ai/server/controller/InserzioneController.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
import java.net.URL;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
Expand All @@ -23,12 +26,15 @@

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
Expand Down Expand Up @@ -165,7 +171,7 @@ public ModelAndView showForm(Map<String, Object> model){
}

@RequestMapping(value="/inserzione",method= RequestMethod.POST)
public ModelAndView processInserzione(InserzioneForm inserzioneForm,BindingResult result,Principal principal){
public ModelAndView processInserzione(InserzioneForm inserzioneForm, BindingResult result,Principal principal){
boolean inserimentoSupermercato=false;
boolean inserimentoInserzione=false;
boolean inserimentoProdotto=false;
Expand Down Expand Up @@ -327,5 +333,91 @@ public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
return new Float(dist).floatValue();
}


@RequestMapping(value="/android/inserzione/getCategorie", method = RequestMethod.GET)
@ResponseBody
public JSONArray getCategorie() {
System.out.println("Called: /android/inserzione/getCategorie");
JSONArray response = new JSONArray();

ArrayList<String> categorieList = new ArrayList<String>();
for(Map.Entry<Integer,Categoria> cat : dati.getCategorie().entrySet()){
response.add(cat.getValue().getNome());
}
return response;
}

@RequestMapping(value="/android/inserzione/checkbarcode/{barcode}", method= RequestMethod.GET)
@ResponseBody
public JSONArray checkbarcode(@PathVariable Long barcode) {
System.out.println("Called: /android/inserzione/checkbarcode " + barcode);
JSONArray response = new JSONArray();
JSONObject jsonObj = new JSONObject();

if(dati.getProdotti().containsKey(barcode)) {
jsonObj.put("descrizione", dati.getProdotti().get(barcode).getDescrizione());
jsonObj.put("trovato", true);
}
else
jsonObj.put("trovato", false);

response.add(jsonObj);
System.out.println("TROVATO:" + jsonObj.get("trovato"));
return response;
}

@RequestMapping(value="/android/inserzione/getSottoCategorie/{categoria}", method = RequestMethod.GET)
@ResponseBody
public JSONArray getSottoCategorieAndroid(@PathVariable String categoria) {
System.out.println("Called: /android/inserzione/getSottoCategorie " + categoria);
JSONArray response = new JSONArray();
for(Map.Entry<Integer, Categoria> c : dati.getCategorie().entrySet())
if(c.getValue().getNome().equals(categoria))
for(Sottocategoria s : (Set<Sottocategoria>) c.getValue().getSottocategorias())
response.add(s.getNome());
return response;
}

@RequestMapping(value="/android/inserzione/getSupermercati")
@ResponseBody
public JSONArray getSupermercatiAndroid(float lat, float lng){
System.out.println("Called: /android/inserzione/getSupermercati " + lat + " - " + lng);
JSONArray response = new JSONArray();
List<JSONObject> jsonObjList = new ArrayList<JSONObject>();
float massimaDistanza = 50000; // distanza = 3 km!
for(Map.Entry<String, Supermercato> s : dati.getSupermercati().entrySet()) {
float distanza = distFromAndroid(lat, lng, s.getValue().getLatitudine().floatValue(), s.getValue().getLongitudine().floatValue());
if( distanza <= massimaDistanza) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("nome", s.getValue().getNome());
jsonObj.put("distanza", distanza);
jsonObjList.add(jsonObj);
}
}

Collections.sort(jsonObjList, new Comparator<JSONObject>(){
@Override
public int compare(JSONObject arg0, JSONObject arg1) {
return (int) (((float) arg0.get("distanza")) - ((float) arg1.get("distanza")));
}});

response.addAll(jsonObjList);
return response;
}

public static float distFromAndroid(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;

int meterConversion = 1609;

return (float) (dist * meterConversion);
}

}
11 changes: 11 additions & 0 deletions src/main/java/ai/server/controller/LoginController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
import java.util.HashMap;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

Expand Down Expand Up @@ -75,5 +77,14 @@ public ModelAndView loginerror(){
public ModelAndView logout(){
return new ModelAndView("index");
}

@RequestMapping(value="/android/login", method = RequestMethod.POST)
@ResponseBody
public Boolean androidLogin(HttpServletRequest request, HttpServletResponse response)
{
System.out.println("sono entrato in login android");

return new Boolean(true);
}

}
66 changes: 60 additions & 6 deletions src/main/java/ai/server/controller/RegisterController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,26 @@
import hibernate.Utente;

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

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






import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.mobile.device.Device;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
Expand Down Expand Up @@ -42,11 +51,7 @@ public void setDati(Dati dati){
}

@RequestMapping(value="/register", method = RequestMethod.GET)
public String showForm(Model model, HttpServletRequest httpServletRequest){
if(httpServletRequest.getParameter("android-device")!=null){
System.out.println("eccoci");
return "eccoci";}

public String showForm(Model model){
Registration registration = new Registration();
model.addAttribute("registration", registration);

Expand All @@ -67,7 +72,7 @@ public void processRegistration(@Valid Registration registration, BindingResult
return;
}
try{
dati.inserisciUtente(registration.getEmail(), registration.getUserName(), registration.getPassword(),new Date(),numerocasuale);
dati.inserisciUtente(registration.getEmail(), registration.getUserName(), registration.getPassword(), new Date(), numerocasuale);
}catch(Exception e){
System.out.println(e.getMessage());
System.out.println(e.getStackTrace());
Expand Down Expand Up @@ -102,4 +107,53 @@ else if(utente.getConfermato() == true)

}


@RequestMapping(value="/android/register", method = RequestMethod.POST)
@ResponseBody
public JSONArray processAndroidRegistration(@Valid Registration registration, BindingResult result, HttpServletRequest request){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
JSONArray response = new JSONArray();
JSONObject jsonObj = new JSONObject();

System.out.println("calling android register");

registrationValidation.validate(registration, result);
String numerocasuale = java.util.UUID.randomUUID().toString();
Map<String, String> errorsMap = new HashMap<String, String>();

if(result.hasErrors()){

jsonObj.put("status", false);

for(FieldError fieldError : result.getFieldErrors())
errorsMap.put(fieldError.getField(), fieldError.getDefaultMessage());
jsonObj.put("errors", errorsMap);
response.add(jsonObj);
return response;

}
try{
dati.inserisciUtente(registration.getEmail(), registration.getUserName(), registration.getPassword(), new Date(), numerocasuale);
}catch(Exception e){
System.out.println(e.getMessage());
System.out.println(e.getStackTrace());
jsonObj.put("status", false);
errorsMap.put("database", e.getMessage());
jsonObj.put("errors", errorsMap);
response.add(jsonObj);
return response;
}

Mail mail = (Mail) context.getBean("mail");

String [] temp = request.getRequestURL().toString().split("/");
String url = temp[0]+"//"+temp[1]+temp[2]+"/"+temp[3]+"/";
mail.sendMail("[email protected]", registration.getEmail(), "Registration Confirmation", "Click the link above to confirm your registration\n\n\n"+"<a href='"+url+"confirmregistration?numeroCasuale="+numerocasuale+"&email="+registration.getEmail()+"' />");
jsonObj.put("status", true);
response.add(jsonObj);
return response;
}



}
Loading

0 comments on commit b03a5e1

Please sign in to comment.