CheckBoxCell in CellTable - gwt

I have a CheckBoxCell I want to add my CellTable but not when I'm wrong because when I run it does not show me the Check
THIS IS MY CODE
public class TablaEntryPoint extends Composite implements EntryPoint{
private SingleSelectionModel sm = new SingleSelectionModel();
{
// Añade un objeto que recibe notificaciones cuando cambia la selección.
sm.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
#Override
public void onSelectionChange(SelectionChangeEvent event) {
AuxParametro c = sm.getSelectedObject();
if (c != null) {
Window.alert(c.getNomParametro());
}
}
});
}
/** La tabla trabaja por páginas. En este caso la longitud de página se pasa en el
* constructor. También hay un constructor sin parámetros que define una longitud
* por defecto de 15 renglones por página. */
private final CellTable<AuxParametro> tblConocidos = new CellTable<AuxParametro>(10);
{
// asigna el objeto que controla las selecciones.
tblConocidos.setSelectionModel(sm);
// Agrega columnas.
// Columna numérica. El constructor de "NumberCell"puede recibir un"NumberFormat".
tblConocidos.addColumn(new Column<AuxParametro, Number>(new NumberCell()) {
{
setHorizontalAlignment(HasAlignment.ALIGN_RIGHT);
}
#Override
public Long getValue(final AuxParametro objeto) {
return objeto.getIdParametro();
}
}, "ID Unico");
// Columna de texto fijo con encabezado y pie de página.
tblConocidos.addColumn(new TextColumn<AuxParametro>() {
#Override
public String getValue(final AuxParametro objeto) {
return objeto.getNomParametro();
}
}, "Nombre Parametro");
/* Columna modificable. El método "update" de la interfaz "FieldUpdater" recibe
* los cambios a un objeto de la columna. */
tblConocidos.addColumn(new Column<AuxParametro,String>(new TextInputCell()) {
{
/* Asigna la referencia al objeto que recibe las notificaciones de cambio. */
setFieldUpdater(new FieldUpdater<AuxParametro, String>() {
#Override
public void update(int index, AuxParametro objeto, String valor) {
objeto.setCodContable(Integer.parseInt(valor));
}
});
}
#Override
public String getValue(final AuxParametro objeto) {
return String.valueOf(objeto.getCodContable());
}
}, "Codigo Contable");
// Columna de fecha.
tblConocidos.addColumn(new Column<AuxParametro, Number>(new NumberCell()) {
#Override
public Integer getValue(final AuxParametro objeto) {
return objeto.getCodUno();
}
}, "Codigo Uno");
// Columna de fecha.
tblConocidos.addColumn(new Column<AuxParametro, Number>(new NumberCell()) {
#Override
public Integer getValue(final AuxParametro objeto) {
return objeto.getCodDos();
}
}, "Codigo Dos");
Column<AuxParametro, Boolean> checkColumn = new Column<AuxParametro, Boolean>(
new CheckboxCell(true, false)) {
#Override
public Boolean getValue(AuxParametro object) {
// Get the value from the selection model.
return sm.isSelected(object);
}
};
tblConocidos.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
}
private final SimplePager pager = new SimplePager();
{
pager.setDisplay(tblConocidos);
}
public TablaEntryPoint(List<AuxParametro> tabla) {
ListDataProvider<AuxParametro> dataProvider = new ListDataProvider<AuxParametro>(tabla);
dataProvider.addDataDisplay(tblConocidos);
FlowPanel panel = new FlowPanel();
panel.add(new Label("Seleccione un contacto o edite su teléfono."));
panel.add(tblConocidos);
panel.add(pager);
initWidget(panel);
}
public void onModuleLoad() {
RootPanel.get().add(this);
}
}

I think you need to set the column width for each of your columns. If you look at the GWT showcase CellTable example (here) you can see that the checkbox column width is set with the statement cellTable.setColumnWidth(checkColumn, 40, Unit.PX).

Related

Huffman code for image compression - Java

Since I started my Codification Theory course, I've started to feel curious about practical implementations of information theory algorithms. I've researched about Huffman code and how this is used for data compress. I am specially curious about building an image (JPG, JPEG) compressor using Huffman codes but I'm struggling in the implementation.
My idea for this program goes like this:
1. Implement a HuffmanCode class, which is used to encode and decode a string input (Find the char frequency for all characters in string, build Huffman tree, generate Huffman code, etc.). I found this implementation "here".
2. Having the Huffman code implementation, I read an image input and convert it to a byte array. Then, I use this byte array to build a string having all of these bytes. Now, I apply the Huffman code for the previous string.
3. The result of the previous step is a binary string, then I convert this binary string to a byte array.
4. Finally, write the corresponding image to the previous byte array and output.
Following this reasoning, I got a RasterFormatException : Data array too small (should be > 749999 ). I've tried others implementations for writing the image but I am still getting some other Exceptions such as image == null exception.
I was wondering if someone has a better approach for building this program, or if I am missing something related to writing/reading images in Java (I'm new with this tools), or if I am misunderstanding something related to Huffman codes.
The HuffmanCode class is the following (I made some changes):
public class HuffmanCode {
public static void main(String[] args){
String test = "AndersonAndresLlanosQuintero";
System.out.println(countFrequency(test));
}
// Clase nodo para las construcción del árbol.
class HuffmanNode{
public int frecuencia;
public char caracter;
public HuffmanNode leftNode;
public HuffmanNode rightNode;
public HuffmanNode(){}
public int getFrecuencia() {
return frecuencia;
}
public void setFrecuencia(int frecuencia) {
this.frecuencia = frecuencia;
}
public char getCaracter() {
return caracter;
}
public void setCaracter(char caracter) {
this.caracter = caracter;
}
public HuffmanNode getLeftNode() {
return leftNode;
}
public void setLeftNode(HuffmanNode leftNode) {
this.leftNode = leftNode;
}
public HuffmanNode getRightNode() {
return rightNode;
}
public void setRightNode(HuffmanNode rightNode) {
this.rightNode = rightNode;
}
}
// Clase comparadora para saber cuando un nodo está por encima de otro.
class HuffmanComparator implements Comparator<HuffmanNode> {
public int compare(HuffmanNode x, HuffmanNode y) {
return x.frecuencia - y.frecuencia;
}
}
/* Procedemos a implementar el algoritmo : */
/* Necesitaremos la raíz del árbol de Huffman y un Map para
hacer match entre un símbol y su frecuencia de aparición.
*/
private Map<Character,String> charToBinaryMap;
private HuffmanNode root;
private String nuevaSalida;
public HuffmanNode getRoot(){
return this.root;
}
public String getNuevaSalida(){
return this.nuevaSalida;
}
public HuffmanCode(){
this.root = null;
this.charToBinaryMap = new HashMap<Character, String>();
}
public HuffmanNode getTree(){
return this.root;
}
/* Teniendo el código de Huffman, decodificar simplemente asigna a cada arista
* del árbol el símbolo de 0 o 1. Para esta implementación, las aristas a la izq.
* tendrán el símbolo "0" y para la derecha el símbolo "1". */
public String Decodificar(String binaryString, HuffmanNode root){
HuffmanNode current = root;
StringBuilder build = new StringBuilder();
for(int i = 0; i < binaryString.length(); i++){
if(current != null){
if((current.rightNode == null && binaryString.charAt(i) == '1') || (current.leftNode == null && binaryString.charAt(i) == '0')){
i--;
build.append(current.caracter);
current = root;
continue;
}
if(binaryString.charAt(i) == '1'){
current = current.rightNode;
}else {
current = current.leftNode;
}
}
}
if(current != null){
build.append(current.caracter);
}
return build.toString();
}
/*Codificar : Crear el árbol más óptimo para nuestra cadena de bits. */
public String Codificar(String strToCode){
Map<Character, Integer> charOcurrence = countFrequency(strToCode);
int n = charOcurrence.size();
/* Creamos una cola de prioridad con el mapeo de la ocurrencia de símbolos
que organice los símbolos de acuerdo al comparador de Huffman. */
PriorityQueue<HuffmanNode> huffmanHeap = new PriorityQueue<>(n, new HuffmanComparator());
// Recorremos el HashMap y creamos la cola de prioridad de acuerdo a la frecuencia del símbolo:
charOcurrence.forEach((key, value) -> {
HuffmanNode node = new HuffmanNode();
node.caracter = key;
node.frecuencia = value;
node.leftNode = null;
node.rightNode = null;
huffmanHeap.add(node);
});
/* Transformamos la cola prioritaria (minHeap) en un árbol de Huffman mediante
el algoritmo visto en clase. */
while(huffmanHeap.size() > 1){
HuffmanNode leaf1 = huffmanHeap.peek();
huffmanHeap.poll();
HuffmanNode leaf2 = huffmanHeap.peek();
huffmanHeap.poll();
HuffmanNode ptr = new HuffmanNode();
ptr.frecuencia = leaf1.frecuencia + leaf2.frecuencia;
ptr.caracter = '-';
ptr.leftNode = leaf1;
ptr.rightNode = leaf2;
huffmanHeap.add(ptr);
}
this.root = huffmanHeap.peek();
/* Teniendo el árbol de Huffman, buscamos las palabras código
y mostramos al usuario como se han codificado los símbolos : */
System.out.println(" Caracter | Palabra Código | Frecuencia");
System.out.println("----------------------------------");
codeWords(root, "");
/* Codificamos el input con las nuevas palabras código obtenidas : */
StringBuilder build = new StringBuilder();
for(Character ch : strToCode.toCharArray()){
build.append(this.charToBinaryMap.get(ch));
}
this.nuevaSalida = build.toString();
int pesoOriginal = strToCode.getBytes().length*8;
int pesoComprimido = nuevaSalida.length();
System.out.println("Peso original (bits) :" + pesoOriginal);
/*System.out.println("Codificación de Huffman: " + nuevaSalida);
*/
System.out.println("Longitud de la codificación de Huffman: " + nuevaSalida.length());
System.out.println("Peso post-codificación: " + pesoComprimido);
return nuevaSalida;
}
/* countFrequency : Cuenta número de ocurrencias de un caracter. */
public static Map<Character, Integer> countFrequency(String input){
HashMap<Character, Integer> mapFrequency = new HashMap<>();
for(int i = 0; i < input.length(); i++){
if(!mapFrequency.containsKey(input.toCharArray()[i])){
mapFrequency.put(input.toCharArray()[i], 1);
}else{
mapFrequency.put(input.toCharArray()[i], mapFrequency.get(input.toCharArray()[i])+1);
}
}
return mapFrequency;
}
/* Como queremos las hojas del árbol de Huffman, hacemos un simple
* recorrido in-order sobre el árbol, imprimiendo únicamente las hojas. */
public void codeWords(HuffmanNode root, String str){
if(root.leftNode != null){
codeWords(root.leftNode, str + 0);
}
if(root.leftNode == null && root.rightNode == null){
this.charToBinaryMap.put(root.caracter, str);
System.out.println(root.caracter + " | " + str + " | " + root.frecuencia);
return;
}
if(root.rightNode != null){
codeWords(root.rightNode, str + 1);
}
}
public String charList(HuffmanNode root, String str){
if(root.leftNode != null){
charList(root.leftNode, str);
}
if(root.leftNode == null && root.rightNode == null){
str = str + root.caracter;
}
if(root.rightNode != null){
charList(root.rightNode, str);
}
return str;
}
}
The ImageProcessing class, where the whole reasoning is developed, is the following:
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.*;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import javax.imageio.ImageIO;
public class ImageProcessing {
public static void main(String args[]) throws Exception{
/* Convert image to byte array and then, to a string */
StringBuilder build = new StringBuilder();
BufferedImage bImage = ImageIO.read(new File("/WorkSpace/HuffmanCompression/src/draken.jpg"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
for(int i = 0; i < data.length; i++){
build.append(data[i]);
}
/* Use Huffman code to the previous string.*/
HuffmanCode huffman = new HuffmanCode();
String prueba = huffman.Codificar(build.toString());
String pruebaDecodificada = huffman.Decodificar(prueba, huffman.getTree());
String strToByte = huffman.getNuevaSalida();
/*
String inputString = strToByte;
Charset dictionaryMap = StandardCharsets.UTF_16;
byte[] newImage = inputString.getBytes(dictionaryMap);
*/
/*Convert the binary string to a byte array and then, output the corresponding image. I copied and paste this part of the code from this blog. */
byte[] bval = new BigInteger(strToByte, 2).toByteArray();
OutputStream stream = new FileOutputStream("output.jpg");
BufferedImage image = createRGBImage(bval, bImage.getWidth(), bImage.getHeight());
try {
ImageIO.write(image, "jpg", stream);
}
finally {
stream.close();
}
}
public static BufferedImage createRGBImage(byte[] bytes, int width, int height) {
DataBufferByte buffer = new DataBufferByte(bytes, bytes.length);
ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[]{8, 8, 8}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
return new BufferedImage(cm, Raster.createInterleavedRaster(buffer, width, height, width * 3, 3, new int[]{0, 1, 2}, null), false, null);
}
}
I will be grateful if someone can help me, Thanks in advance!

Sort list items based on gps distance

Hello the dart code below contains a series of locations with the gps position, at the time of starting the app I have to retrieve the long and lat that I have saved in two variables, what I have to do next is to sort the list of locations based on the gps distance from where to find me this is based on lat and long how can I do?
Dart Code:
double longitudine=0,latitudine=0;
Future<bool> caricamentoSedi() async {
await _getGpsValue();
listaSedi = await Sede.caricamento();
//This point write function order listaSedi
return true;
}
Sede class:
class Sede {
//Costruttore di una sede
Sede(this.info_id, this.app_id, this.info_title, this.descrizione, this.email,
this.telefono, this.lat, this.long, this.note,this.rgbcolor);
final int info_id, app_id;
double lat = 0, long = 0;
final String info_title, descrizione, email, telefono, note,rgbcolor;
//Descrizione: Funzione che effettua il caricamento delle sedi
static Future<List<Sede>> caricamento() async {
return await SedeController.caricamento();
}
//Descrizione: funzione che recupero l'email
String getEmail() {
return email;
}
//Descrizione: funzione che recupera la descrizione
String getDescrizione() {
return descrizione;
}
//Descrizione: funzione che recupera il numero di telefono rimuovendo li spazi vuoti presenti nel valore
String getTelefono() {
return telefono.replaceAll(new RegExp(r"\s+"), "");
}
//Recupero latitudine
double getLatitudine() {
return lat;
}
//Recupero longitudine
double getLongitudine() {
return long;
}
//Recupero note
String getNote() {
return this.note;
}
}
You can implement your own method to calculate distance between 2 points, then use it to sort the list :
https://stackoverflow.com/a/64966888/14394936
Or you can use a lib like geolocator :
https://stackoverflow.com/a/64890616/14394936
Sort the list :
https://stackoverflow.com/a/12889025/14394936
https://api.dart.dev/stable/2.10.5/dart-core/List/sort.html

Network Lobby manager

I'm developing a multiplayer online application with unity3D, and I'm using networkLobbyManager, I managed to create a match and allow the players to join the match by running matchMaker.JoinMatch so I have all the players in "Lobby Scene" but I did not understand how we can join them in "play scene".
(I have found that we can move to play scene only if all players are ready, but I do not understand how I can put them all ready). my code :
public InputField impF;
public InputField impF1;
public Dropdown d;
List<MatchInfoSnapshot> m;
MatchInfoSnapshot ma;
public int n = 1;
// Use this for initialization
public void enableMatch()
{
Debug.Log("# MMStart ");
this.StartMatchMaker();
}
public override void OnStartHost()
{
base.OnStartHost();
Debug.Log("the game has created");
}
public void crereMatch()
{
string nom = impF.text;
Debug.Log(nom);
MMCreateMateches(nom);
n = 2;
}
public void findMtches()
{
MMListMateches();
}
public void joinMatch()
{
Debug.Log(d.options[d.value].text);
foreach (var match in this.matches)
{
Debug.Log("dans la boucle des matches");
Debug.Log(match.name);
if ((d.options[d.value].text).Equals(match.name))
{
//on récupere
ma = match;
Debug.Log("dans le if " + ma.name);
break;
}
}
// this.f
m = this.matches;
ma = m.Find(x => (x.name).Equals(ma.name));
Debug.Log("apres recuperation de la liste" + ma.name);
MMjoinMateches(ma);
}
void MMListMateches()
{
Debug.Log("# MMListMateches ");
this.matchMaker.ListMatches(0, 20, "", true, 0, 0, OnMatchList);
}
public override void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matchList)
{
Debug.Log("# OnMatchList ");
base.OnMatchList(success, extendedInfo, matchList);
if (!success)
{
Debug.Log("liste failed " + extendedInfo);
}
else
{
if (matches.Count > 0)
{ //les matches en cours > 0 ms on doit le joiner
Debug.Log("succesfully listed match 1 er match :" + matchList[0]);
Debug.Log(matchList[0].name);
foreach (var match in this.matches)
{
Debug.Log("dans la boucle");
Debug.Log(match.name);
Debug.Log(" wééééééééééééééééééé ");
}
d.ClearOptions();
foreach (var match in this.matches)
{
Debug.Log(match.name);
// impF1.text = match.name;
List<string> m_DropOptions = new List<string> { match.name };
d.AddOptions(m_DropOptions);
}
// MMjoinMateches(matchList[0]);
}
else
{
Debug.Log("no mateches");
// MMCreateMateches();
}
}
}
void MMjoinMateches(MatchInfoSnapshot firstMatch)
{
Debug.Log("# MMjoinMateches ");
this.matchMaker.JoinMatch(firstMatch.networkId, "", "", "", 0, 0, OnMatchJoined);
}
public override void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
{
Debug.Log("# OnMatchJoined ");
base.OnMatchJoined(success, extendedInfo, matchInfo);
if (!success)
{
Debug.Log("failed to join match " + extendedInfo);
impF1.text = "failed";
}
else
{
Debug.Log("succesfuly joined match " + matchInfo.networkId);
impF1.text = "succes";
this.StartClient(matchInfo);
}
}
void MMCreateMateches(string nom)
{
Debug.Log("# MMCreateMateches ");
Debug.Log(nom);
this.matchMaker.CreateMatch(nom, 15, true, "", "", "", 0, 0, OnMatchCreate);
}
public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
{
Debug.Log("# OnMatchCreate ");
base.OnMatchCreate(success, extendedInfo, matchInfo);
if (!success)
{
Debug.Log("failed to create match " + extendedInfo);
}
else
{
Debug.Log("succesfuly created match " + matchInfo.networkId);
OnStartHost();
}
}
public override void OnLobbyServerPlayersReady()
{
base.OnLobbyServerPlayersReady();
}
Watch this tutorial by Holistic 3D on how to setup Unity Network Lobby (Free in the Asset Store). https://www.youtube.com/watch?v=jklWlm5v21k
In the settings, you determine Max Players needed to enter a room. You can set it to '1' so anyone can enter at anytime.
Change Max Players from 4 to 1 See Link

Android GCM crashes when app is stopped

I’m trying to implement an Android app with GCM (Google Cloud Messaging).
My specific Server is written by PHP and my Client is an Android app.
Push notification messages are received well when the app is running. The logcat is this:
07-28 07:49:56.991: V/GCMBroadcastReceiver(13254): onReceive: com.google.android.c2dm.intent.RECEIVE
07-28 07:49:56.991: V/GCMRegistrar(13254): Setting the name of retry receiver class to com.appacoustic.android.g.gcm.GGCMBroadcastReceiver
07-28 07:49:57.011: D/GGCMBroadcastReceiver(13254): Servicio: com.appacoustic.android.g.gcm.GGCMIntentService
07-28 07:49:57.011: V/GCMBroadcastReceiver(13254): GCM IntentService class: com.appacoustic.android.g.gcm.GGCMIntentService
07-28 07:49:57.021: V/GCMBaseIntentService(13254): Intent service name: GCMIntentService-<<<MyProjectNumber>>>-1
07-28 07:49:57.026: D/GGCMIntentService(13254): Mensaje recibido: <<<MySendedMessage>>>
but when it is stopped (not paused), if I send a message from the host, appears the typical Toast crash.
The logcat error is this:
07-28 07:50:06.381: V/GCMBroadcastReceiver(13294): onReceive: com.google.android.c2dm.intent.RECEIVE
07-28 07:50:06.386: V/GCMRegistrar(13294): Setting the name of retry receiver class to com.appacoustic.android.g.gcm.GGCMBroadcastReceiver
07-28 07:50:06.386: D/GGCMBroadcastReceiver(13294): Servicio: com.appacoustic.android.g.gcm.GGCMIntentService
07-28 07:50:06.386: V/GCMBroadcastReceiver(13294): GCM IntentService class: com.appacoustic.android.g.gcm.GGCMIntentService
07-28 07:50:06.396: D/AndroidRuntime(13294): Shutting down VM
07-28 07:50:06.396: W/dalvikvm(13294): threadid=1: thread exiting with uncaught exception (group=0x4163bc50)
07-28 07:50:06.401: E/AndroidRuntime(13294): FATAL EXCEPTION: main
07-28 07:50:06.401: E/AndroidRuntime(13294): Process: com.planetdevices.android.loyalty, PID: 13294
07-28 07:50:06.401: E/AndroidRuntime(13294): java.lang.RuntimeException: Unable to instantiate service com.appacoustic.android.g.gcm.GGCMIntentService: java.lang.NullPointerException
I guess the issue is about wake up the Service, but actually I test too much things and I am really confused and exhausted…
I have made a package in a library project to implement GCM. The code is this:
GGCMIntentService.java
package com.appacoustic.android.g.gcm;
...
/**
* #author AppAcoustiC <p>
* Servicios GCM. Básicamente son todo callbacks.
*/
public class GGCMIntentService extends GCMBaseIntentService {
private static final String tag = "GGCMIntentService";
/**
* Constructor.
*/
public GGCMIntentService() {
super(SENDER_ID); // Llamamos a la superclase
} // GGCMIntentService()
/**
* Es lo que hace al registrarse el dispositivo.
*/
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(tag, "Dispositivo registrado: regId = " + registrationId);
Log.d("name: ", GGCM.name);
Log.d("email: ", GGCM.email);
displayMessage(context, getString(R.string.gcm_registered)); // Mostramos un mensaje informativo por pantalla
GServerUtilities.register(context, registrationId, GGCM.name, GGCM.email); // Nos registramos en nuestro Servidor dedicado (Planet Devices)
} // onRegistered()
/**
* Es lo que se hace al eliminar el registro.
*/
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(tag, "Eliminado el registro del dispositivo.");
displayMessage(context, getString(R.string.gcm_unregistered)); // Mostramos un mensaje informativo por pantalla
if (GCMRegistrar.isRegisteredOnServer(context)) { // Si ya está registrado en nuestro Servidor
GServerUtilities.unregister(context, registrationId); // Se desregistra de éste
} else {
// Este callback se hace al tratar de borrar el registro desde la clase ServerUtilities cuando el registro en el Servidor falla
Log.i(tag, "Se ha ignorado el callback de anulación de registro.");
}
} // onUnregistered()
/**
* Notificación recibida.
*/
#Override
protected void onMessage(Context context, Intent intent) {
String message = intent.getStringExtra(GCommonUtilities.EXTRA_MESSAGE); // Recojo el mensaje
Log.d(tag, "Mensaje recibido: " + message);
displayMessage(context, message); // Lo mostramos por pantalla
generateNotification(context, message); // Se lo notificamos al usuario (mensaje emergente)
} // onMessage()
/**
* Cuando se borran los mensajes.
*/
#Override
protected void onDeletedMessages(Context context, int total) {
Log.i(tag, "Recibida la notificación de mensajes eliminados.");
String message = getString(R.string.gcm_deleted, total); // Recojo el string y el nº de mensajes borrados SERÁ SIEMPRE EL MISMO STRING AL COGERLO DE LOS R.STRING ???
displayMessage(context, message); // Lo mostramos por pantalla
generateNotification(context, message); // Se lo notificamos al usuario (mensaje emergente)
} // onDeletedMessages()
/**
* Al producirse un error.
*/
#Override
public void onError(Context context, String errorId) {
Log.i(tag, "Error recibido: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId)); // Lo mostramos por pantalla
} // onError()
/**
* Al producirse un error recuperable.
*/
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.i(tag, "Recibido error recuperable: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error, errorId)); // Lo mostramos por pantalla
return super.onRecoverableError(context, errorId); // Devolvemos un booleano para saber como ha ido la cosa
} // onRecoverableError()
/**
* Genera una notificación para que el usuario sea informado de que ha recibido un mensaje.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher; // Icono que aparece en la barra de notificaciones (será el de la app desde donde creemos el objeto GGCM)
long when = System.currentTimeMillis(); // Instante en el que se produce la notificación
// Creamos la notificación:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name); // Título de la notificación (Nombre de la app)
// Gestionamos el Intent de la notificación:
Intent notificationIntent = new Intent(context, GGCM.NotificationActivity); // Lo configuramos para que empiece una nueva Actividad (NotificationActivity)
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND; // Sonido de notificación por defecto
// ¡¡¡ POR SI QUEREMOS USAR NUESTRO PROPIO SONIDO PERSONALIZADO !!!
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
notification.defaults |= Notification.DEFAULT_VIBRATE; // Vibra (si la vibración está activa, claro)
notificationManager.notify(0, notification); // Notificamos (con todos los parámetros incluidos)
} // generateNotification()
} // GGCMIntentService
GGCM.java
package com.appacoustic.android.g.gcm;
...
/**
* #author AppAcoustiC <p>
* Engloba todo lo que conlleva el sistema Google Cloud Messaging.
*/
public class GGCM {
private final String tag = "GGCM";
private Context context;
// Variables que meteremos en la base de datos de nuestro Servidor particular:
static String name;
static String email;
static Class<?> NotificationActivity;
AsyncTask<Void, Void, Void> mRegisterTask; // Tarea de registro
AsyncTask<Void, Void, Void> mUnregisterTask; // Tarea de eliminación del registro
/**
* Constructor.
* #param context Contexto de la Actividad.
* #param SERVER_URL Base URL del Servidor (directorio raíz).
* #param SENDER_ID ID del proyecto en cuestión registrado para usar GCM.
* #param userName Nombre del usuario de la aplicación.
* #param cls Actividad que se inicia al pulsar las notificaciones recibidas.
*/
public GGCM(final Context context,
String SERVER_URL,
String SENDER_ID,
String userName,
Class<?> cls) {
// Primero de nada, comprobamos que está todo en orden para que el GCM funcione.
// Qué el dispositivo soporta GCM y que el Manifest está bien configurado. Esto, una vez testeado se puede comentar:
//checker(context);
// Comprobacion rutinaria de que tenemos inicializadas la variables que indican el Servidor y el ID del proyecto GCM:
G_A.checkNotNull(SERVER_URL, "SERVER_URL");
G_A.checkNotNull(SENDER_ID, "SENDER_ID");
// Asignamos los parámetros a las variables que usamos dentro del paquete:
this.context = context;
GCommonUtilities.SERVER_URL = SERVER_URL;
GCommonUtilities.SENDER_ID = SENDER_ID;
name = userName;
email = G_A.getEmailAdress(context);
NotificationActivity = cls;
// Comprobamos la conexión a internet:
GConnectionDetector gCD = new GConnectionDetector(context);
if (!gCD.isConnectingToInternet()) { // Si no hay internet
// Creamos nuestro Diálogo de alerta particular
GAlertDialog.showAlertDialog(context,
"Error de conexión a Internet",
"Por favor, conéctese para poder hacer uso de la aplicación.",
false);
return; // Paramos la ejecución del programa
}
context.registerReceiver(mHandleMessageReceiver, new IntentFilter(GCommonUtilities.DISPLAY_MESSAGE_ACTION)); // Registramos el receptor
} // GGCM()
/**
* Registra el dispositivo en el que está instalada la app.
*/
public void registerDevice() {
final String regId = GCMRegistrar.getRegistrationId(context); // Obtenemos el ID de registro
if (regId.equals("")) { // Si es "" es que aún no estamos registrados
GCMRegistrar.register(context, GCommonUtilities.SENDER_ID); // Nos registramos
Log.i(tag, "Nos acabamos de registrar en el GCM.");
} else {
// El dispositivo ya está registrado. Comprobamos el Servidor:
if (GCMRegistrar.isRegisteredOnServer(context)) {
// Nos saltamos el registro en el Servidor. Simplemente mostramos un mensaje por pantalla:
G_A.showToast(context, context.getString(R.string.already_registered), Toast.LENGTH_SHORT);
Log.i(tag, "Ya está registrado en nuestro Servidor.");
} else {
// Tratamos de registrarnos de nuevo. Hay que hacerlo mediante una Tarea Asíncrona:
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
boolean registered = GServerUtilities.register(context, regId, name, email);
// Si llegados a este punto, todos los intentos de registrar el dispositivo a nuestro Servidor (Planet Devices) fallan,
// necesitaremos desregistrar el dispositivo desde GCM. La aplicación tratará de registrarse de nuevo cuando se reinicie.
// Hay que tener en cuenta que GCM enviará una devolución de llamada (callback) de borrado de registro al finalizar,
// pero GGCMIntentService.onUnregistered() lo ignorará:
if (!registered) {
GCMRegistrar.unregister(context); // Eliminamos el registro
}
return null;
} // doInBackground()
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null; // Liberamos memoria
} // onPostExecute()
};
mRegisterTask.execute(null, null, null); // Ejecutamos la tarea
}
}
} // registerDevice()
/**
* Elimina el registro del dispositivo que tiene instalada la aplicación.
*/
public void unregisterDevice() {
final String regId = GCMRegistrar.getRegistrationId(context); // Obtenemos el ID de registro
//GServerUtilities.unregister(context, regId);
if (regId.equals("")) { // Si es "" es que aún no estamos registrados
Log.i(tag, "Nos estamos aún registrados. No se puede anular el registro.");
G_A.showToast(context, context.getString(R.string.already_unregistered), Toast.LENGTH_SHORT); // ESTO NO FUNCIONA COMO BEBERÍA !!!
} else {
// Tratamos de eliminar el registro. Hay que hacerlo mediante una Tarea Asíncrona:
mUnregisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
GServerUtilities.unregister(context, regId); // Nos "desregistramos"
return null;
} // doInBackground()
#Override
protected void onPostExecute(Void result) {
mUnregisterTask = null; // Liberamos memoria
} // onPostExecute()
};
mUnregisterTask.execute(null, null, null); // Ejecutamos la tarea
}
} // unregisterDevice()
/**
* Comprobamos si el dispositivo soporta GCM y que el Manifest está bien configurado.
*/
private void checker(Context context) {
try {
GCMRegistrar.checkDevice(context);
Log.i(tag, "El dispositivo soporta GCM.");
GCMRegistrar.checkManifest(context);
Log.i(tag, "El Manifest está correctamente.");
} catch (UnsupportedOperationException e) {
Log.e(tag, "El dispositivo no soporta GCM.", e);
} catch (IllegalStateException e) {
Log.e(tag, "El Manifest no está bien configurado.", e);
}
} // checker()
/**
* Manejador para recibir mensajes.
*/
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(GCommonUtilities.EXTRA_MESSAGE); // Recogemos el mensaje
GWakeLocker.acquire(context); // Mantenemos el dispositivo a la espera de que acabe de procesar todo el mensaje (para que no entre en modo de suspensión)
// SI TENEMOS ESTO PUESTO MUESTRA TOAST CADA VEZ QUE ENVIAMOS UNA NOTIFICACIÓN PUSH !!!!!:
//G_A.showToast(context, newMessage, Toast.LENGTH_SHORT); // Lo mostramos por pantalla
GWakeLocker.release(); // Liberamos para ahorrar energía (importante para optimizar los recursos de la batería)
} // onReceive()
};
/**
* Realiza las acciones pertinentes cuando se hace un callback de onDestroy desde la Actividad que llama al objeto GGCM.
*/
public void setOnDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true); // Cancelamos la Tarea de registro
}
context.unregisterReceiver(mHandleMessageReceiver); // Desregistramos el manejador de mensajes ?????????????????? ESTO CREO QUE HAY QUE QUITARLO, SINO NO LLEGARÁN LOS MENSAJES EMERGENTES
GCMRegistrar.onDestroy(context); // Destruimos
} // setOnDestroy()
} // GGCM
GCommonUtilities.java
package com.appacoustic.android.g.gcm;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* #author AppAcoustiC <p>
* Utilidades comunes a todo el paquete. Las cargamos en el contructor de GGCM al hacer la llamada.
*/
public final class GCommonUtilities {
static String SERVER_URL; // Base URL del Servidor
static String SENDER_ID; // ID del proyecto en cuestión registrado para usar GCM
// Intentos usados para mostrar un mensaje en la pantalla:
static final String DISPLAY_MESSAGE_ACTION = "com.appacoustic.android.g.gcm.DISPLAY_MESSAGE"; // Nombre del paquete
static final String EXTRA_MESSAGE = "message"; // Extra
/**
* Notifica a la interfaz de usuario (UI) que tiene que mostrar un mensaje.<p>
* Este método está definido en el Helper común porque es usado por ambos: la interfaz de usuario y el Servicio.
* #param context Contexto de la actividad.
* #param message Mensaje a mostrar.
*/
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); // Instanciamos el intento
intent.putExtra(EXTRA_MESSAGE, message); // Añadimos el mensaje que hemos metido como parámetro
context.sendBroadcast(intent); // Hace el envío asíncrono
} // displayMessage()
} // GCommonUtilities
GGCMBroadcastReceiver.java
package com.appacoustic.android.g.gcm;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBroadcastReceiver;
/**
* #author AppAcoustiC <p>
* Implementa el receptor de GCM.<p>
* De este modo irá al paquete donde tenemos nosotros nuestro GCMIntentService.
*/
public class GGCMBroadcastReceiver extends GCMBroadcastReceiver {
private final String tag = "GGCMBroadcastReceiver";
/**
* Devuelve el nombre de la clase donde tenemos implementado el servicio.
*/
#Override
protected String getGCMIntentServiceClassName(Context context) {
String s = GGCMIntentService.class.getName();
Log.d(tag, "Servicio: " + s);
return s;
} // getGCMIntentServiceClassName()
} // GGCMBroadcastReceiver
GServerUtilities.java
package com.appacoustic.android.g.gcm;
...
import com.appacoustic.android.g.R;
import com.google.android.gcm.GCMRegistrar;
/**
* #author AppAcoustiC <p>
* Utilidades de comunicación con nuestro Servidor (Planet Devices).
*/
public final class GServerUtilities {
private static final String TAG = "GServerUtilities";
private static final int MAX_ATTEMPTS = 5; // Nº máximo de intentos
private static final int BACKOFF_MILLI_SECONDS = 2000; // Tiempo para echarse atrás
private static final Random random = new Random(); // Objeto auxiliar para generar números aleatorios
/**
* Registra el dispositivo en nuestro Servidor.
* #param context Contexto de la Actividad.
* #param regId ID de registro.
* #param name Nombre del usuario.
* #param email Email del usuario.
* #return Si el registro ha sido correcto.
*/
static boolean register(final Context context, final String regId, String name, String email) {
Log.i(TAG, "Registrando dispositivo... (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/register.php"; // Dirección donde tenemos el *.php que implementa el registro
// Parámetros:
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId); // ID de registro
params.put("name", name); // Nombre
params.put("email", email); // Email
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Tiempo para echarse atrás (y un poco más cada vez)
// Una vez GCM devuelve el ID de registro, necesitamos registrar dicho ID en nuestro Servidor particular:
for (int i = 1; i <= MAX_ATTEMPTS; i++) { // Si el Servidor ha caído, lo volveremos a intentar alguna vez más
Log.d(TAG, "Intento de registro nº " + i + ".");
try {
displayMessage(context, context.getString(R.string.server_registering, i, MAX_ATTEMPTS)); // Mostramos por pantalla
post(serverUrl, params); // Hacemos el post con los parámetros hacia nuestro Servidor
GCMRegistrar.setRegisteredOnServer(context, true); // Indicamos que se registra
// Mostramos por pantalla que todo ha ido bien:
String message = context.getString(R.string.server_registered);
GCommonUtilities.displayMessage(context, message);
return true;
} catch (IOException e) {
// Aquí estamos simplificando el manejo de errores. En una aplicación real
// se debería de volver a procesar sólo los errores recuperables (como HTTP error code 503, e.g.):
Log.e(TAG, "Fallo tratando de registrarse. Nº de intento: " + i, e);
if (i == MAX_ATTEMPTS) {
break; // Si ya hemos gastado todos los intentos, paramos la aplicación
}
try {
Log.d(TAG, "Parando por " + backoff + " ms antes de volver a intentar.");
Thread.sleep(backoff); // Retardo
} catch (InterruptedException e1) {
Log.d(TAG, "Hilo interrumpido: Abortamos los restantes intentos.");
Thread.currentThread().interrupt(); // Actividad terminada antes de que la hayamos completado
return false;
}
backoff *= 2; // Incrementamos exponencialemente el tiempo de espera
}
}
// Si hemos llegado hasta aquí es porque hemos condumido todos los intentos.
// Mostramos que ha habido un error:
String message = context.getString(R.string.server_register_error, MAX_ATTEMPTS);
GCommonUtilities.displayMessage(context, message);
return false;
} // register()
/**
* Anula el registro del par "cuenta-dispositivo" en nuestro Servidor.
* #param context Contexto de la Actividad.
* #param regId ID de registro.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "Anulando el registro del dispositivo... (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister.php"; // Archivo *.php encargado de implementar el proceso
// Parámetros:
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId); // Sólo hace falta el ID de registro para eliminarlo
try {
post(serverUrl, params); // Hacemos el post con los parámetros hacia nuestro Servidor
GCMRegistrar.setRegisteredOnServer(context, false); // Indicamos que se desregistra
// Mostramos por pantalla que todo ha ido bien:
String message = context.getString(R.string.server_unregistered);
GCommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// En este punto, el dispositivo está desregistrado de GCM, pero permanece registrado en nuestro Servidor de Planet Devices.
// Podríamos tratar de anular el registro de nuevo, pero no es necesario, ya que si el Servidor trata de enviar un mensaje al dispositivo,
// se generará un mensaje de error tipo "No registrado" y se debería de anular el registro del dispositivo.
// Mostramos que ha habido un error anulando el registro:
String message = context.getString(R.string.server_unregister_error, e.getMessage());
GCommonUtilities.displayMessage(context, message);
}
} // unregister()
/**
* Realiza un POST a nuestro Servidor.
* #param endpoint Dirección del POST.
* #param params Parámetros de la solicitud.
* #throws IOException
*/
private static void post(String endpoint, Map<String, String> params) throws IOException {
URL url; // Dirección del POST
try {
url = new URL(endpoint); // La inicializamos
} catch (MalformedURLException e) {
throw new IllegalArgumentException("URL incorrecta: " + endpoint); // La dirección no es correcta
}
// Creamos un StringBuilder para cargar el contenido del POST:
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// Construimos el cuerpo del POST usando los parámetros:
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString(); // Pasamos a un único String todo el StringBuilder
Log.v(TAG, "Enviando '" + body + "' a " + url);
byte[] bytes = body.getBytes(); // Convertimos a bytes para que puedan viajar por la red mdiante un Stream
HttpURLConnection conn = null; // Conexión
try {
// Abrimos la conexión y la configuramos:
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// Posteamos la solicitud:
OutputStream out = conn.getOutputStream(); // Instanciamos el flujo
out.write(bytes); // Enviamos los datos
out.close(); // Cerramos el Stream
// Manejamos la respuesta:
int status = conn.getResponseCode(); // Obtenemos el código de respuesta desde el Servidor (el 200 indica que todo ha ido bien)
if (status != 200) { // Si no es el código 200, es porque ha habido un error
throw new IOException("Envío fallido con error de código: " + status);
}
} finally {
if (conn != null) {
conn.disconnect(); // Al final desconectamos
}
}
} // post()
} // GServerUtilities
I have written an Android app which calls the library like that:
Call in onCreate()
// Creamos nuestro objeto GCM:
gGCM = new GGCM(context,
Att.SERVER_URL,
Att.SENDER_ID,
Att.userName,
NotificationActivity.class);
//gGCM.registerDevice(); // Nos registramos directamente
//gGCM.unregisterDevice();
I have a NotificationActivity which is the Activity which is thrown when you click the push notification and so on...
Finally my Manifest is here:
AndroidMainfest.xml
...
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<!-- GCM requiere de una cuenta Google -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Se activa cuando se recibe un mensaje -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Crea un permiso específico para este paquete. Sólo esta app puede recibir estos mensajes -->
<permission
android:name="com.planetdevices.android.loyalty.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.planetdevices.android.loyalty.permission.C2D_MESSAGE" />
<!-- Esta aplicación tiene permiso para registrarse y recibir mensajes de datos de Google -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Pemisos del estado de la red para detectar el status de Internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Vibración -->
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="Splash"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/Splash" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="MainActivity" android:screenOrientation="portrait"></activity>
<activity android:name="NotificationActivity" android:screenOrientation="portrait"></activity>
...
<!-- Receptor -->
<receiver
android:name="com.appacoustic.android.g.gcm.GGCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.appacoustic.android.g.gcm" />
</intent-filter>
</receiver>
<!-- Servicio -->
<service android:name="com.appacoustic.android.g.gcm.GGCMIntentService" />
</application>
</manifest>
Thank you so much for your help!
I’ve changed calling to SuperClass Constructor in GGCMIntentService. I have put directly the SENDER_ID as a String with its value. I have done it because when I stop the app, when that Constructor is called, throws a nullPointerException, because String “SENDER_ID” is not initialized.
public GGCMIntentService() {
//super(SENDER_ID); // Llamamos a la superclase
super("<<<ProjectNumber>>>"); // NEW WAY
} // GGCMIntentService()
After that, for a similar reason, I’ve put also directly Activity to start in the same Class in method generateNotification() like this:
Class<?> cls = null;
try {
cls = Class.forName("<<<packageName>>>.NotificationActivity");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
I have put this instance a little lines below:
Intent notificationIntent = new Intent(context, cls);
It’s not the best solution, but it works perfectly whenever. :-)

Symfony2 Validator ExecutionContextInterface in cascade

i try to use a function for validate a sub form.
the subform is persisted in cascade with parent entity, with OneToOne relation.
In the top of my entity :
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;
On the bottom, the function :
public function verifyCommandeTypeValide(ExecutionContextInterface $context)
{
die('ok');
$valide = false;
if($this->getLivraison() === true){
$valide = true;
if(preg_match("/^[0-9]$/", $this->getLivraisondelais())){
$context->addViolationAt('livraisondelais','Le délais de livraison ne doit contenir que des chiffres.');
}
if($this->getLivraisonprice() === null){
$context->addViolationAt('livraisonprice','Vous devez définir les frais de livraison.');
}
}
if($this->getRetrait() === true){
$valide = true;
if(preg_match("/^[0-9]$/", $this->getRetraitdelais())){
$context->addViolationAt('retraitdelais','Le délais de retrait ne doit contenir que des chiffres.');
}
}
if($valide === false){
$context->addViolationAt('livraison','Vous devez définir une méthode de retrait pour le produit.');
}
}
And validation.yml :
YOU\ProductBundle\Entity\CommandeType :
constraints:
- Callback:
methods: [verifyCommandeTypeValide]
YOU\ProductBundle\Entity\Product:
properties:
titre:
- Length :
min : 3
max: 150
maxMessage : "Le titre du produit ne dois pas dépasser 150 caractères."
minMessage : "Le titre du produit dois faire plus de 3 caractères."
- NotBlank :
message : "Vous devez donner un titre au produit."
cat1:
- NotNull :
message : "Vous devez compléter la catégorie de niveau 1 au minimum."
images:
- Count :
min : 1
max : 5
minMessage : "Vous devez mettre 1 photo au minimum."
maxMessage : "Le nombre de photos est limité à 5."
If i try to use constraints callback in the first form layer, in : YOU\ProductBundle\Entity\Product
This work, the callback is executed.
But the callback is not executed for : YOU\ProductBundle\Entity\CommandeType
Anyone know how i can use it with the relation OneToOne ?
thx
need to add : 'cascade_validation' => true,
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'YOU\ProductBundle\Entity\Product',
'cascade_validation' => true,
));
}