dijkstra Algorithm Java Implementation with no libraries used - dijkstra

Implementation of Dijkstra's in java without using Comparator interface.

First you can read here the algorithm Pseudocode: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
End here is one good working impemetation with comparator..but you have to create classes of node , graph etc..
if comparator is your problem just create your own! ;)
static class distance_Comparator implements Comparator<node>
{
public int compare(node x, node y)
{
if(x.getDistance()<y.getDistance())
{
return -1;
}
else if(x.getDistance()>y.getDistance())
{
return 1;
}
return 0;
}
}
And here the Dijkstra
public static void Dijkstra(graph newgraph)
{
System.out.println("--------------------------------------------------------------------------------------");
System.out.println("--------------------------------------------------------------------------------------");
System.out.println("Running Dijkstra . . . .");
System.out.println("--------------------------------------------------------------------------------------");
System.out.println("--------------------------------------------------------------------------------------");
int sum_average_path=0,average_path=0,numberof_paths=0;
long time_a=System.nanoTime();
//[newgraph.getNum_nodes()]; // shortest known distance from "vertex"
//HashMap visited=new HashMap<>();//[newgraph.getNum_nodes()]; // all false initially
//[newgraph.getNum_nodes()]; // preceeding node in path
distance_Comparator comparator=new distance_Comparator();
PriorityQueue<node> queue = new PriorityQueue<node>((int) newgraph.getNumber_of_nodes(),comparator);
///////// find max shortest path : diameter of graph ////////////////
double diameter=-1.0;
int s=0,i=0;
double alt=0;
HashMap map;
///////////find all nodes of graph/////////////////
map=newgraph.getAll_graph_nodes();
for (Object key : map.keySet())
{
i++;
// System.out.println("source node: "+key);
///////////////////Initializations////////////////////////////
/////////////////////////////////////////////////////////////
HashMap distance=new HashMap<>(16,0.6f);
HashMap previous=new HashMap<>(16,0.6f);
node tmpnode=(node)map.get(key);
for (Object key_other : map.keySet())
{
node x_tmpnode=(node)map.get(key_other);
distance.put(key_other, Double.POSITIVE_INFINITY);
x_tmpnode.setDistance(Double.POSITIVE_INFINITY);
x_tmpnode.setVisited(false);
}
tmpnode.setDistance_table(distance);
tmpnode.setPrevious_table(previous);
/////////////////////////////////////end of init//////////////////////////////
tmpnode.setDistance((double)(0));
queue.offer(tmpnode); //add tmp node to PriorityQueue
distance.put(key,(double)(0));
Stack sta=new Stack();
while(queue.isEmpty()==false)
{
Stack stack_prev=new Stack();
node queue_tmpnode=queue.poll(); //min_node(distance,map);////vertex in Q with smallest distance in dist[] and has not been visited;
queue_tmpnode.setVisited(true);
/* if(queue_tmpnode.getPrevious_table()!=null)
{
// System.out.println("pre: "+prev);
Stack tmp=(Stack)tmpnode.getPrevious_table().get(queue_tmpnode.getName());
while(tmp.empty()==false)
{
sta.add(queue_tmpnode.getName());
//System.out.println("pop: "+tmp.pop().toString());
queue_tmpnode=
}
}*/
HashMap queue_tmpnodemap=(HashMap)queue_tmpnode.getMap();
if(queue_tmpnodemap!=null)
{
//////////////find all Neighbours of node queue_tmpnode////////////////////
for (Object v : queue_tmpnodemap.keySet())
{
// System.out.println(" v: "+ v.toString());
node tmpnode_neighbors=(node)map.get(v);
alt=(double)(queue_tmpnode.getDistance()) ;
edge tmp_edge= (edge) (queue_tmpnodemap.get(v)); // dist_between(u, v); --accumulate shortest dist from source
alt+= tmp_edge.getWeight();
if ( (alt < tmpnode_neighbors.getDistance()))
{
tmpnode_neighbors.setDistance(alt); // keep the shortest dist from src to v
distance.put(v, alt);
/*
stack_prev.add(tmpnode_neighbors.getName());
HashMap pre_map=new HashMap();
pre_map.put(queue_tmpnode.getName(), stack_prev);
previous.put(tmpnode_neighbors.getName(), pre_map);
//System.out.println("prev stack: "+stack_prev.size());
tmpnode.setPrevious_table(previous);
* */
if((tmpnode_neighbors.isVisited()==false))
queue.add(tmpnode_neighbors); // Add unvisited v into the Q to be processed
}
}
}
}
HashMap tmp_d=null;
tmp_d=new HashMap();
for(Object x: distance.keySet())
{
if(Double.parseDouble(distance.get(x).toString()) < Double.POSITIVE_INFINITY && Double.parseDouble(distance.get(x).toString())!=0)
{
//System.out.println("U: "+key+"-> V:"+x+" value: "+t_tmpnode.getDistance_table().get(x));
tmp_d.put(x, distance.get(x));
}
}
// System.out.println("V:"+i+" size:"+tmp_d.size()+" capacity:");
distance.clear();
tmpnode.setDistance_table(tmp_d);
}
System.out.println("---------------Dijkstra algorithm-------------");
for (Object key : map.keySet())
{
node tmpnode=(node)map.get(key);
// System.out.println("distance of: "+key.toString()+" , is: ");
//System.out.print("U: "+key);
if(tmpnode.getDistance_table()!= null)
{
//System.out.println(" dipla monopatia: "+(tmpnode.getShortest_paths_number()-tmpnode.getDistance_table().size()));
for(Object x: tmpnode.getDistance_table().keySet())
{
//if(Double.parseDouble(tmpnode.getDistance_table().get(x).toString()) < Double.POSITIVE_INFINITY && Double.parseDouble(tmpnode.getDistance_table().get(x).toString())!=0)
//System.out.println("U: "+key+"-> V:"+x+" value: "+tmpnode.getDistance_table().get(x));
if(diameter < (double)tmpnode.getDistance_table().get(x))
{
diameter= (double)tmpnode.getDistance_table().get(x);
}
sum_average_path+=(double)tmpnode.getDistance_table().get(x);
numberof_paths++;
}
}
System.out.println("\n--------------------------------------------");
for(Object prev: tmpnode.getPrevious_table().keySet())
{
System.out.print("node: "+tmpnode.getName()+" path: ");
HashMap map_prev=(HashMap)tmpnode.getPrevious_table().get(prev);
for(Object prev_path: map_prev.keySet())
{
System.out.println("V: "+prev+" -> "+prev_path+"");
Stack tmp=(Stack) map_prev.get(prev_path);
System.out.println("stacksize: "+tmp.size());
while(tmp.empty()==false)
{
System.out.println("pop: "+tmp.pop().toString());
}
}
}
}
newgraph.setDiameter(diameter);
System.out.println("Graph diameter is: "+newgraph.getDiameter());
System.out.println("average path lenght: "+((double)((double)sum_average_path/(double)numberof_paths)));
long time_b=System.nanoTime();
System.out.println("Dijkstra time: "+(time_b-time_a)+" time in seconds: "+(double)((time_b-time_a)/1000000000.0));
}
class: node.java
import java.util.HashMap;
public class node {
private int name;
private HashMap map;
private double pagerank_old;
private double pagerank_new;
private double point_to_me;
private HashMap point_to_me_table;
private double point_to_other;
private HashMap betweenness;
private double betweenness_ofvertex;
private int num_nodes;
private double cluster_coefficient;
private int index;
private int lowlink;
private int shortest_paths_number;
private double distance;
private boolean visited;
private int hub_score;
private int auth_score;
private HashMap distance_table;
private HashMap previous_table;
//private edge edge;
public node(int name,HashMap map)
{
this.name=name;
this.map=map;
}
public node(int name)
{
this.name=name;
}
/**
* #return the name
*/
public int getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(int name) {
this.name = name;
}
/**
* #return the map
*/
public HashMap getMap() {
return map;
}
/**
* #param map the map to set
*/
public void setMap(HashMap map) {
this.map = map;
}
/**
* #return the pagerank_old
*/
public double getPagerank_old() {
return pagerank_old;
}
/**
* #param pagerank_old the pagerank_old to set
*/
public void setPagerank_old(double pagerank_old) {
this.pagerank_old = pagerank_old;
}
/**
* #return the pagerank_new
*/
public double getPagerank_new() {
return pagerank_new;
}
/**
* #param pagerank_new the pagerank_new to set
*/
public void setPagerank_new(double pagerank_new) {
this.pagerank_new = pagerank_new;
}
/**
* #return the pont_to_me
*/
public double getPoint_to_me() {
return point_to_me;
}
/**
* #param pont_to_me the pont_to_me to set
*/
public void setPoint_to_me(double pont_to_me) {
this.point_to_me = pont_to_me;
}
/**
* #return the point_to_other
*/
public double getPoint_to_other() {
return point_to_other;
}
/**
* #param point_to_other the point_to_other to set
*/
public void setPoint_to_other(double point_to_other) {
this.point_to_other = point_to_other;
}
/**
* #return the distance
*/
public double getDistance() {
return distance;
}
/**
* #param distance the distance to set
*/
public void setDistance(double distance) {
this.distance = distance;
}
/**
* #return the visited
*/
public boolean isVisited() {
return visited;
}
/**
* #param visited the visited to set
*/
public void setVisited(boolean visited) {
this.visited = visited;
}
/**
* #return the distance_table
*/
public HashMap getDistance_table() {
return distance_table;
}
/**
* #param distance_table the distance_table to set
*/
public void setDistance_table(HashMap distance_table) {
this.distance_table = distance_table;
}
/**
* #return the previous_table
*/
public HashMap getPrevious_table() {
return previous_table;
}
/**
* #param previous_table the previous_table to set
*/
public void setPrevious_table(HashMap previous_table) {
this.previous_table = previous_table;
}
public int getHub_score()
{
return hub_score;
}
public void setHub_score(int sc)
{
this.hub_score=sc;
}
public int getAuth_score()
{
return auth_score;
}
public void setAuth_score(int sc)
{
this.auth_score=sc;
}
/**
* #return the point_to_me_table
*/
public HashMap getPoint_to_me_table() {
return point_to_me_table;
}
/**
* #param point_to_me_table the point_to_me_table to set
*/
public void setPoint_to_me_table(HashMap point_to_me_table) {
this.point_to_me_table = point_to_me_table;
}
/**
* #return the betweenness
*/
public HashMap getBetweenness() {
return betweenness;
}
/**
* #param betweenness the betweenness to set
*/
public void setBetweenness(HashMap betweenness) {
this.betweenness = betweenness;
}
/**
* #return the cluster_coefficient
*/
public double getCluster_coefficient() {
return cluster_coefficient;
}
/**
* #param cluster_coefficient the cluster_coefficient to set
*/
public void setCluster_coefficient(double cluster_coefficient) {
this.cluster_coefficient = cluster_coefficient;
}
/**
* #return the betweenness_ofvertex
*/
public double getBetweenness_ofvertex() {
return betweenness_ofvertex;
}
/**
* #param betweenness_ofvertex the betweenness_ofvertex to set
*/
public void setBetweenness_ofvertex(double betweenness_ofvertex) {
this.betweenness_ofvertex = betweenness_ofvertex;
}
/**
* #return the shortest_paths_number
*/
public int getShortest_paths_number() {
return shortest_paths_number;
}
/**
* #param shortest_paths_number the shortest_paths_number to set
*/
public void setShortest_paths_number(int shortest_paths_number) {
this.shortest_paths_number = shortest_paths_number;
}
/**
* #return the num_nodes
*/
public int getNum_nodes() {
return num_nodes;
}
/**
* #param num_nodes the num_nodes to set
*/
public void setNum_nodes(int num_nodes) {
this.num_nodes = num_nodes;
}
/**
* #return the index
*/
public int getIndex() {
return index;
}
/**
* #param index the index to set
*/
public void setIndex(int index) {
this.index = index;
}
/**
* #return the lowlink
*/
public int getLowlink() {
return lowlink;
}
/**
* #param lowlink the lowlink to set
*/
public void setLowlink(int lowlink) {
this.lowlink = lowlink;
}
}
class: edge
public class edge {
private int a;
private int b;
private double weight;
//private double betweenness;
public edge(int start,int end,double weight){
this.a=start;
this.b=end;
this.weight=weight;
}
/**
* #return the a
*/
public int getA() {
return a;
}
/**
* #param a the a to set
*/
public void setA(int a) {
this.a = a;
}
/**
* #return the b
*/
public int getB() {
return b;
}
/**
* #param b the b to set
*/
public void setB(int b) {
this.b = b;
}
/**
* #return the weight
*/
public double getWeight() {
return weight;
}
/**
* #param weight the weight to set
*/
public void setWeight(double weight) {
this.weight = weight;
}
}
class: graph
import java.util.HashMap;
import java.util.Stack;
public class graph {
private HashMap all_graph_nodes;
private double number_of_nodes;
private double number_of_edges;
private double diameter;
private double average_degre;
private double density;
private int nodeindex;
private Stack tarjanStack;
public graph(HashMap map,double n_nodes,double m_edges)
{
this.all_graph_nodes=map;
this.number_of_nodes=n_nodes;
this.number_of_edges=m_edges;
}
/**
* #return the all_graph_nodes
*/
public HashMap getAll_graph_nodes() {
return all_graph_nodes;
}
/**
* #param all_graph_nodes the all_graph_nodes to set
*/
public void setAll_graph_nodes(HashMap all_graph_nodes) {
this.all_graph_nodes = all_graph_nodes;
}
/**
* #return the number_of_nodes
*/
public double getNumber_of_nodes() {
return number_of_nodes;
}
/**
* #param number_of_nodes the number_of_nodes to set
*/
public void setNumber_of_nodes(double number_of_nodes) {
this.number_of_nodes = number_of_nodes;
}
/**
* #return the number_of_edges
*/
public double getNumber_of_edges() {
return number_of_edges;
}
/**
* #param number_of_edges the number_of_edges to set
*/
public void setNumber_of_edges(double number_of_edges) {
this.number_of_edges = number_of_edges;
}
/**
* #return the diameter
*/
public double getDiameter() {
return diameter;
}
/**
* #param diameter the diameter to set
*/
public void setDiameter(double diameter) {
this.diameter = diameter;
}
/**
* #return the average_degre
*/
public double getAverage_degre() {
return average_degre;
}
/**
* #param average_degre the average_degre to set
*/
public void setAverage_degre(double average_degre) {
this.average_degre = average_degre;
}
/**
* #return the density
*/
public double getDensity() {
return density;
}
/**
* #param density the density to set
*/
public void setDensity(double density) {
this.density = density;
}
/**
* #return the nodeindex
*/
public int getNodeindex() {
return nodeindex;
}
/**
* #param nodeindex the nodeindex to set
*/
public void setNodeindex(int nodeindex) {
this.nodeindex = nodeindex;
}
/**
* #return the tarjanStack
*/
public Stack getTarjanStack() {
return tarjanStack;
}
/**
* #param tarjanStack the tarjanStack to set
*/
public void setTarjanStack(Stack tarjanStack) {
this.tarjanStack = tarjanStack;
}
}

Related

avro schema LocalDate mapping

How to map avro schema to a LocalDate / LocaldateTime?
The spec says we can use logicalType. But DOES NOT CARE TO SHOW AN EXAMPLE of how it maps to LocalDate in Java. Why is a good example not part of the spec? that is for the specwriters.
Anyay
e.g.
{"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "date", "type": "int", "logicalType": "date"}
]
}
This maps to int and not to LocalDate e.g,
How to map in avro schema LocalDate?
#org.apache.avro.specific.AvroGenerated
public class User extends org.apache.avro.specific.SpecificRecordBase implements
org.apache.avro.specific.SpecificRecord {
private int date;// This should be LocalDate
}
{
"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{
"name": "date",
"type": {
"type": "int",
"logicalType": "date"
}
}
]
}
//this will generate following mapping to private java.time.LocalDate date;as below with maven-avro-plugin.
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package example.avro;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
#org.apache.avro.specific.AvroGenerated
public class User extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -2875816324033601436L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"User\",\"namespace\":\"example.avro\",\"fields\":[{\"name\":\"date\",\"type\":{\"type\":\"int\",\"logicalType\":\"date\"}}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
static {
MODEL$.addLogicalTypeConversion(new org.apache.avro.data.TimeConversions.DateConversion());
}
private static final BinaryMessageEncoder<User> ENCODER =
new BinaryMessageEncoder<User>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<User> DECODER =
new BinaryMessageDecoder<User>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* #return the message encoder used by this class
*/
public static BinaryMessageEncoder<User> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* #return the message decoder used by this class
*/
public static BinaryMessageDecoder<User> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {#link SchemaStore}.
* #param resolver a {#link SchemaStore} used to find schemas by fingerprint
* #return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<User> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<User>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this User to a ByteBuffer.
* #return a buffer holding the serialized data for this instance
* #throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a User from a ByteBuffer.
* #param b a byte buffer holding serialized data for an instance of this class
* #return a User instance decoded from the given buffer
* #throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static User fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.time.LocalDate date;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public User() {}
/**
* All-args constructor.
* #param date The new value for date
*/
public User(java.time.LocalDate date) {
this.date = date;
}
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return date;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
private static final org.apache.avro.Conversion<?>[] conversions =
new org.apache.avro.Conversion<?>[] {
new org.apache.avro.data.TimeConversions.DateConversion(),
null
};
#Override
public org.apache.avro.Conversion<?> getConversion(int field) {
return conversions[field];
}
// Used by DatumReader. Applications should not call.
#SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: date = (java.time.LocalDate)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'date' field.
* #return The value of the 'date' field.
*/
public java.time.LocalDate getDate() {
return date;
}
/**
* Sets the value of the 'date' field.
* #param value the value to set.
*/
public void setDate(java.time.LocalDate value) {
this.date = value;
}
/**
* Creates a new User RecordBuilder.
* #return A new User RecordBuilder
*/
public static example.avro.User.Builder newBuilder() {
return new example.avro.User.Builder();
}
/**
* Creates a new User RecordBuilder by copying an existing Builder.
* #param other The existing builder to copy.
* #return A new User RecordBuilder
*/
public static example.avro.User.Builder newBuilder(example.avro.User.Builder other) {
if (other == null) {
return new example.avro.User.Builder();
} else {
return new example.avro.User.Builder(other);
}
}
/**
* Creates a new User RecordBuilder by copying an existing User instance.
* #param other The existing instance to copy.
* #return A new User RecordBuilder
*/
public static example.avro.User.Builder newBuilder(example.avro.User other) {
if (other == null) {
return new example.avro.User.Builder();
} else {
return new example.avro.User.Builder(other);
}
}
/**
* RecordBuilder for User instances.
*/
#org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<User>
implements org.apache.avro.data.RecordBuilder<User> {
private java.time.LocalDate date;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$);
}
/**
* Creates a Builder by copying an existing Builder.
* #param other The existing Builder to copy.
*/
private Builder(example.avro.User.Builder other) {
super(other);
if (isValidValue(fields()[0], other.date)) {
this.date = data().deepCopy(fields()[0].schema(), other.date);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
}
/**
* Creates a Builder by copying an existing User instance
* #param other The existing instance to copy.
*/
private Builder(example.avro.User other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.date)) {
this.date = data().deepCopy(fields()[0].schema(), other.date);
fieldSetFlags()[0] = true;
}
}
/**
* Gets the value of the 'date' field.
* #return The value.
*/
public java.time.LocalDate getDate() {
return date;
}
/**
* Sets the value of the 'date' field.
* #param value The value of 'date'.
* #return This builder.
*/
public example.avro.User.Builder setDate(java.time.LocalDate value) {
validate(fields()[0], value);
this.date = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'date' field has been set.
* #return True if the 'date' field has been set, false otherwise.
*/
public boolean hasDate() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'date' field.
* #return This builder.
*/
public example.avro.User.Builder clearDate() {
fieldSetFlags()[0] = false;
return this;
}
#Override
#SuppressWarnings("unchecked")
public User build() {
try {
User record = new User();
record.date = fieldSetFlags()[0] ? this.date : (java.time.LocalDate) defaultValue(fields()[0]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
#SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<User>
WRITER$ = (org.apache.avro.io.DatumWriter<User>)MODEL$.createDatumWriter(SCHEMA$);
#Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
#SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<User>
READER$ = (org.apache.avro.io.DatumReader<User>)MODEL$.createDatumReader(SCHEMA$);
#Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}

Doctrine ODM EmbedOne to EmbedMany

I use Mongodb with Doctrine2 to log actions on appointments fot stats purpose. I had to modify the Entity from
class Appointment {
/** #ODM\Id */
protected $id;
/** #ODM\EmbedOne(targetDocument="Product") */
private $product;
to
class Appointment {
/** #ODM\Id */
protected $id;
/** #ODM\EmbedMany(targetDocument="Product") */
private $products;
So earlier one appointment had one product, but now one appointment may have multiple products. Every things work fine while saving.
My question is how do I update the old documents 'product' to put them also into an array?
Regards Andrea
You can use the migration features described here: http://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/migrating-schemas.html
In your case, you can update your Doctrine document this way:
<?php
class Appointment
{
/**
* ODM\EmbedOne(targetDocument="Product")
* #ODM\NotSaved
*/
protected $product;
/**
* #ODM\EmbedMany(targetDocument="Product")
*/
protected $products;
/**
* #ODM\AlsoLoad({"product"})
*/
public function populateProducts($product)
{
$this->products = [$product];
$this->product = null;
}
/**
* #ODM\AlsoLoad({"product"})
*/
public function populateProducts($product)
{
$this->products = [$product];
}
}
This way, the old single product is cast to a collection of products.
<?php
namespace Application\Entity\Documents;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* #ODM\Document(collection="appointment")
*/
class Appointment {
/** #ODM\Id */
protected $id;
/** #ODM\String #ODM\Index */
protected $department;
/** #ODM\String #ODM\Index */
protected $action;
/** #ODM\Int #ODM\Index */
protected $idAppointment;
/** #ODM\String */
protected $service_order;
/** #ODM\Int */
protected $sales_order;
/** #ODM\String */
protected $access_number;
/** #ODM\String */
protected $so_type;
/** #ODM\String */
protected $stage;
/** #ODM\String */
protected $se_items;
/** #ODM\String #ODM\Index */
protected $id_va;
/** #ODM\String */
protected $id_icms;
/** #ODM\String */
protected $company;
/** #ODM\String */
protected $customer_name;
/** #ODM\String */
protected $street;
/** #ODM\String */
protected $housenumber;
/** #ODM\String */
protected $building;
/** #ODM\String */
protected $appartment;
/** #ODM\String */
protected $postal_code;
/** #ODM\String */
protected $city;
/** #ODM\String */
protected $email;
/** #ODM\String */
protected $contact_number;
/** #ODM\String */
protected $ref_isp;
/** #ODM\String */
protected $comment;
/** #ODM\Date */
protected $first_available_schedule;
/** #ODM\Date */
protected $request_cancellation;
/** #ODM\Boolean */
protected $asap;
/** #ODM\String */
protected $allday;
/** #ODM\String #ODM\Index */
protected $operator;
/** #ODM\String */
protected $createdBy;
/** #ODM\String */
protected $movedBy;
/** #ODM\String */
protected $network;
/** #ODM\Date #ODM\Index */
private $created;
/** #ODM\Date #ODM\Index */
private $posted;
/** #ODM\String */
protected $actionBy;
/** #ODM\EmbedOne(targetDocument="Schedule") */
private $schedule;
/**
* #ODM\EmbedOne(targetDocument="Product")
* #ODM\NotSaved
*/
protected $product;
/** #ODM\EmbedMany(targetDocument="Product") */
private $products = array();
/**
* #ODM\AlsoLoad({"product"})
*/
public function populateProducts($product) {
$this->products = [$product];
$this->product = null;
}
/** #ODM\String */
protected $mqMsg;
public function __construct() {
$this->products = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId() {
return $this->id;
}
public function getDepartment() {
return $this->department;
}
public function getAction() {
return $this->action;
}
public function getIdAppointment() {
return $this->idAppointment;
}
public function getService_order() {
return $this->service_order;
}
public function getSales_order() {
return $this->sales_order;
}
public function getAccess_number() {
return $this->access_number;
}
public function getSo_type() {
return $this->so_type;
}
public function getStage() {
return $this->stage;
}
public function getSe_items() {
return $this->se_items;
}
public function getId_va() {
return $this->id_va;
}
public function getId_icms() {
return $this->id_icms;
}
public function getCompany() {
return $this->company;
}
public function getCustomer_name() {
return $this->customer_name;
}
public function getStreet() {
return $this->street;
}
public function getHousenumber() {
return $this->housenumber;
}
public function getBuilding() {
return $this->building;
}
public function getAppartment() {
return $this->appartment;
}
public function getPostal_code() {
return $this->postal_code;
}
public function getCity() {
return $this->city;
}
public function getEmail() {
return $this->email;
}
public function getContact_number() {
return $this->contact_number;
}
public function getRef_isp() {
return $this->ref_isp;
}
public function getComment() {
return $this->comment;
}
public function getFirst_available_schedule() {
return $this->first_available_schedule;
}
public function getRequest_cancellation() {
return $this->request_cancellation;
}
public function getAsap() {
return $this->asap;
}
public function getAllday() {
return $this->allday;
}
public function getOperator() {
return $this->operator;
}
public function getCreatedBy() {
return $this->createdBy;
}
public function getMovedBy() {
return $this->movedBy;
}
public function getNetwork() {
return $this->network;
}
public function getCreated() {
return $this->created;
}
public function getPosted() {
return $this->posted;
}
public function getActionBy() {
return $this->actionBy;
}
public function getSchedule() {
return $this->schedule;
}
public function getProduct() {
return $this->product;
}
public function getProducts() {
return $this->products;
}
public function getMqMsg() {
return $this->mqMsg;
}
public function setId($id) {
$this->id = $id;
}
public function setDepartment($department) {
$this->department = $department;
}
public function setAction($action) {
$this->action = $action;
}
public function setIdAppointment($idAppointment) {
$this->idAppointment = $idAppointment;
}
public function setService_order($service_order) {
$this->service_order = $service_order;
}
public function setSales_order($sales_order) {
$this->sales_order = $sales_order;
}
public function setAccess_number($access_number) {
$this->access_number = $access_number;
}
public function setSo_type($so_type) {
$this->so_type = $so_type;
}
public function setStage($stage) {
$this->stage = $stage;
}
public function setSe_items($se_items) {
$this->se_items = $se_items;
}
public function setId_va($id_va) {
$this->id_va = $id_va;
}
public function setId_icms($id_icms) {
$this->id_icms = $id_icms;
}
public function setCompany($company) {
$this->company = $company;
}
public function setCustomer_name($customer_name) {
$this->customer_name = $customer_name;
}
public function setStreet($street) {
$this->street = $street;
}
public function setHousenumber($housenumber) {
$this->housenumber = $housenumber;
}
public function setBuilding($building) {
$this->building = $building;
}
public function setAppartment($appartment) {
$this->appartment = $appartment;
}
public function setPostal_code($postal_code) {
$this->postal_code = $postal_code;
}
public function setCity($city) {
$this->city = $city;
}
public function setEmail($email) {
$this->email = $email;
}
public function setContact_number($contact_number) {
$this->contact_number = $contact_number;
}
public function setRef_isp($ref_isp) {
$this->ref_isp = $ref_isp;
}
public function setComment($comment) {
$this->comment = $comment;
}
public function setFirst_available_schedule($first_available_schedule) {
$this->first_available_schedule = $first_available_schedule;
}
public function setRequest_cancellation($request_cancellation) {
$this->request_cancellation = $request_cancellation;
}
public function setAsap($asap) {
$this->asap = $asap;
}
public function setAllday($allday) {
$this->allday = $allday;
}
public function setOperator($operator) {
$this->operator = $operator;
}
public function setCreatedBy($createdBy) {
$this->createdBy = $createdBy;
}
public function setMovedBy($movedBy) {
$this->movedBy = $movedBy;
}
public function setNetwork($network) {
$this->network = $network;
}
public function setCreated($created) {
$this->created = $created;
}
public function setPosted($posted) {
$this->posted = $posted;
}
public function setActionBy($actionBy) {
$this->actionBy = $actionBy;
}
public function setSchedule($schedule) {
$this->schedule = $schedule;
}
public function setProduct($product) {
$this->product = $product;
}
public function setProducts($products) {
$this->products = $products;
}
public function setMqMsg($mqMsg) {
$this->mqMsg = $mqMsg;
}
public function addProduct($product) {
$this->products[] = $product;
}
}
/** #ODM\EmbeddedDocument */
class Schedule {
/** #ODM\Id */
protected $id;
/** #ODM\String */
protected $layer;
/** #ODM\String */
protected $team;
/** #ODM\String */
protected $disponibility;
/** #ODM\Date #ODM\Index */
protected $duedate;
/** #ODM\Date #ODM\Index */
protected $dueperiod;
/** #ODM\Boolean */
protected $is_task;
function getId() {
return $this->id;
}
function getLayer() {
return $this->layer;
}
function getTeam() {
return $this->team;
}
function getDisponibility() {
return $this->disponibility;
}
function getDuedate() {
return $this->duedate;
}
function getDueperiod() {
return $this->dueperiod;
}
function getIs_task() {
return $this->is_task;
}
function setId($id) {
$this->id = $id;
}
function setLayer($layer) {
$this->layer = $layer;
}
function setTeam($team) {
$this->team = $team;
}
function setDisponibility($disponibility) {
$this->disponibility = $disponibility;
}
function setDuedate($duedate) {
$this->duedate = $duedate;
}
function setDueperiod($dueperiod) {
$this->dueperiod = $dueperiod;
}
function setIs_task($is_task) {
$this->is_task = $is_task;
}
}
/** #ODM\EmbeddedDocument */
class Product {
/** #ODM\Id */
protected $id;
/** #ODM\String */
protected $category;
/** #ODM\String */
protected $disponibility;
/** #ODM\String */
protected $abbr;
/** #ODM\Float */
protected $freeze_day;
/** #ODM\Boolean */
protected $regulated;
/** #ODM\Int */
protected $sla;
function getId() {
return $this->id;
}
function getCategory() {
return $this->category;
}
function getDisponibility() {
return $this->disponibility;
}
function getAbbr() {
return $this->abbr;
}
function getFreeze_day() {
return $this->freeze_day;
}
function getSenumber() {
return $this->senumber;
}
function getRegulated() {
return $this->regulated;
}
public function getSla() {
return $this->sla;
}
function setId($id) {
$this->id = $id;
}
function setCategory($category) {
$this->category = $category;
}
function setDisponibility($disponibility) {
$this->disponibility = $disponibility;
}
function setAbbr($abbr) {
$this->abbr = $abbr;
}
function setFreeze_day($freeze_day) {
$this->freeze_day = $freeze_day;
}
function setSenumber($senumber) {
$this->senumber = $senumber;
}
function setRegulated($regulated) {
$this->regulated = $regulated;
}
public function setSla($sla) {
$this->sla = $sla;
}
}

Error Iterable Implementation GWTP-Rest Jackson

I use GWT 2.6.1 with GWTP-Rest Api, when i compile, i get an error.
My class Page implements Iterable & Serializable. This class come from the spring framework but was adaptable to GWT (this class is use by an other project which works with RPC. The error comes from an other class "Sort" which implements the same Interface. See code below.
Error come from com.github.nmorel.gwtjackson.rebind.ObjectMapperGenerator which create an exception.
if I delete the Iterator implementation of OrderMobile, no error occure.
Error in console :
Creating deserializer for **.***.**.**.**.***.*****.Page
[INFO] [ERROR] Wrong number of argument for a java.lang.Iterable implementation
Code from Sort :
public class SortMobile implements Serializable, Iterable<OrderMobile>
{
private static final long serialVersionUID = -8226494389482286795L;
public static final Direction DEFAULT_DIRECTION = Direction.ASC;
private List<OrderMobile> orders = new ArrayList<OrderMobile>();
SortMobile() {
}
/**
* Creates a new {#link Sort} instance using the given {#link Order}s.
*
* #param orders must not be {#literal null}.
*/
public SortMobile(final OrderMobile... orders) {
this(Arrays.asList(orders));
}
/**
* Creates a new {#link SortMobile} instance.
*
* #param list must not be {#literal null} or contain {#literal null}.
*/
public SortMobile(final List<OrderMobile> list) {
if (null == list || list.isEmpty()) {
throw new IllegalArgumentException("You have to provide at least one sort property to sort by!");
}
this.orders = list;
}
/**
* Creates a new {#link SortMobile} instance. Order defaults to {#value Direction#ASC}.
*
* #param properties must not be {#literal null} or contain {#literal null} or empty strings
*/
public SortMobile(final String... properties) {
this(DEFAULT_DIRECTION, properties);
}
/**
* Creates a new {#link SortMobile} instance.
*
* #param direction defaults to {#linke Sort#DEFAULT_DIRECTION} (for {#literal null} cases, too)
* #param properties must not be {#literal null} or contain {#literal null} or empty strings
*/
public SortMobile(final Direction direction, final String... properties) {
this(direction, properties == null ? new ArrayList<String>() : Arrays.asList(properties));
}
/**
* Creates a new {#link SortMobile} instance.
*
* #param direction
* #param properties
*/
public SortMobile(final Direction direction, final List<String> properties) {
if (properties == null || properties.isEmpty()) {
throw new IllegalArgumentException("You have to provide at least one property to sort by!");
}
this.orders = new ArrayList<OrderMobile>(properties.size());
for (String property : properties) {
this.orders.add(new OrderMobile(direction, property));
}
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof SortMobile)) {
return false;
}
SortMobile that = (SortMobile) obj;
return this.orders.equals(that.orders);
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
int result = 17;
result = 31 * result + orders.hashCode();
return result;
}
// GETTER SETTER
public void setOrders(final List<OrderMobile> orders) {
this.orders = orders;
}
public List<OrderMobile> getOrders() {
return orders;
}
public static Direction getDefaultDirection() {
return DEFAULT_DIRECTION;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return Arrays.toString(orders.toArray(new OrderMobile[orders.size()]));
}
// ### elements of iterator implementation
#Override
public Iterator<OrderMobile> iterator() {
return this.orders.iterator();
}
/**
* Returns a new {#link Sort} consisting of the {#link Order}s of the current {#link Sort} combined with the given
* ones.
*
* #param sort can be {#literal null}.
* #return
*/
public SortMobile and(final SortMobile sort) {
if (sort == null) {
return this;
}
ArrayList<OrderMobile> these = new ArrayList<OrderMobile>(this.orders);
for (OrderMobile order : sort) {
these.add(order);
}
return new SortMobile(these);
}
/**
* Returns the order registered for the given property.
*
* #param property
* #return
*/
public OrderMobile getOrderFor(final String property) {
for (OrderMobile order : this) {
if (order.getProperty().equals(property)) {
return order;
}
}
return null;
}
}
OrderMobile is a simple dto :
public class OrderMobile implements Serializable {
private static final long serialVersionUID = 1522511010900108987L;
private static final Direction DEFAULT_DIRECTION = Direction.ASC;
private Direction direction;
private String property;
OrderMobile() {
super();
}
/**
* Creates a new {#link OrderMobile} instance. if order is {#literal null} then order defaults to
* {#link SortMobile#DEFAULT_DIRECTION}
*
* #param direction can be {#literal null}, will default to {#link SortMobile#DEFAULT_DIRECTION}
* #param property must not be {#literal null} or empty.
*/
public OrderMobile(final Direction direction, final String property) {
if (!hasText(property)) {
throw new IllegalArgumentException("Property must not null or empty!");
}
this.direction = direction == null ? DEFAULT_DIRECTION : direction;
this.property = property;
}
private boolean hasText(final String s) {
return s != null && s.trim().length() > 0;
}
/**
* Creates a new {#link OrderMobile} instance. Takes a single property. Direction defaults to
* {#link SortMobile#DEFAULT_DIRECTION}.
*
* #param property must not be {#literal null} or empty.
*/
public OrderMobile(final String property) {
this(DEFAULT_DIRECTION, property);
}
/**
* Returns the order the property shall be sorted for.
*
* #return
*/
public Direction getDirection() {
return direction;
}
public void setDirection(final Direction direction) {
this.direction = direction;
}
/**
* Returns the property to order for.
*
* #return
*/
public String getProperty() {
return property;
}
public void setProperty(final String property) {
this.property = property;
}
/**
* Returns whether sorting for this property shall be ascending.
*
* #return
*/
public boolean isAscending() {
return this.direction.equals(Direction.ASC);
}
/**
* Returns a new {#link OrderMobile} with the given {#link OrderMobile}.
*
* #param order
* #return
*/
public OrderMobile with(final Direction order) {
return new OrderMobile(order, this.property);
}
/**
* Returns a new {#link SortMobile} instance for the given properties.
*
* #param properties
* #return
*/
public SortMobile withProperties(final String... properties) {
return new SortMobile(this.direction, properties);
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
int result = 17;
result = 31 * result + direction.hashCode();
result = 31 * result + property.hashCode();
return result;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof OrderMobile)) {
return false;
}
OrderMobile that = (OrderMobile) obj;
return this.direction.equals(that.direction) && this.property.equals(that.property);
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return property + ":" + direction;
}
}
3.Code of Page :
public class PageMobile<T> implements Iterable<T>, Serializable {
private static final long serialVersionUID = 867755909294344406L;
private List<T> content = new ArrayList<T>();
private PageRequestMobile pageable;
private long total;
// for serialization
PageMobile() {
}
/**
* Constructor of {#code Page}.
*
* #param content the content of this page, must not be {#literal null}.
* #param pageable the paging information, can be {#literal null}.
* #param total the total amount of items available
*/
public PageMobile(final List<T> content, final PageRequestMobile pageable, final long total) {
if (null == content) {
throw new IllegalArgumentException("Content must not be null!");
}
this.content.addAll(content);
this.total = total;
this.pageable = pageable;
}
/**
* Creates a new {#link PageMobile} with the given content. This will result in the created {#link PageMobile} being
* identical
* to the entire {#link List}.
*
* #param content must not be {#literal null}.
*/
public PageMobile(final List<T> content) {
this(content, null, null == content ? 0 : content.size());
}
/**
* Returns the number of the current page. Is always non-negative and less that {#code Page#getTotalPages()}.
*
* #return the number of the current page
*/
public int getNumber() {
return pageable == null ? 0 : pageable.getPageNumber();
}
/**
* Returns the size of the page.
*
* #return the size of the page
*/
public int getSize() {
return pageable == null ? 0 : pageable.getPageSize();
}
/*
* (non-Javadoc)
*
* #see org.springframework.data.domain.Page#getTotalPages()
*/
public int getTotalPages() {
return getSize() == 0 ? 0 : (int) Math.ceil((double) total / (double) getSize());
}
/**
* Returns the number of elements currently on this page.
*
* #return the number of elements currently on this page
*/
public int getNumberOfElements() {
return content.size();
}
/**
* Returns the total amount of elements.
*
* #return the total amount of elements
*/
public long getTotalElements() {
return total;
}
/**
* set the total amount of elements.
*
*
*/
public void setTotalElements(final Long total) {
this.total = total;
}
/*
* (non-Javadoc)
*
* #see org.springframework.data.domain.Page#hasPreviousPage()
*/
public boolean hasPreviousPage() {
return getNumber() > 0;
}
/*
* (non-Javadoc)
*
* #see org.springframework.data.domain.Page#isFirstPage()
*/
public boolean isFirstPage() {
return !hasPreviousPage();
}
/*
* (non-Javadoc)
*
* #see org.springframework.data.domain.Page#hasNextPage()
*/
public boolean hasNextPage() {
return (getNumber() + 1) * getSize() < total;
}
/*
* (non-Javadoc)
*
* #see org.springframework.data.domain.Page#isLastPage()
*/
public boolean isLastPage() {
return !hasNextPage();
}
/**
* Returns the page content as {#link List}.
*
* #return
*/
public List<T> getContent() {
return Collections.unmodifiableList(content);
}
/*
* (non-Javadoc)
*
* #see org.springframework.data.domain.Page#hasContent()
*/
public boolean hasContent() {
return !content.isEmpty();
}
/*
* (non-Javadoc)
*
* #see org.springframework.data.domain.Page#getSort()
*/
// FIXME to the version in
public SortMobile getSort() {
return pageable == null ? null : pageable.getSort();
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
String contentType = "UNKNOWN";
if (content.size() > 0) {
contentType = content.get(0).getClass().getName();
}
return "Page " + getNumber() + " of " + getTotalPages() + " containing " + contentType + " instances";
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof PageMobile<?>)) {
return false;
}
PageMobile<?> that = (PageMobile<?>) obj;
boolean totalEqual = this.total == that.total;
boolean contentEqual = this.content.equals(that.content);
boolean pageableEqual = this.pageable == null ? that.pageable == null : this.pageable.equals(that.pageable);
return totalEqual && contentEqual && pageableEqual;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
int result = 17;
result = 31 * result + (int) (total ^ total >>> 32);
result = 31 * result + (pageable == null ? 0 : pageable.hashCode());
result = 31 * result + content.hashCode();
return result;
}
/**
* Adjust the page size, distributing items equally (+/- 1 item) on each page, given a maximum page size.
*
* WARNING: this function reverse pages order.
* TODO: delegate page order reversing to another function, to limit a single behavior for a given function.
*
* #param page The page
* #param request The associated page request
* #param maxPageSize The maximum page size
* #return The new ajusted page
*/
public static <T> PageMobile<T> adjustPageSize(final PageMobile<T> page, final PageRequestMobile request, final int maxPageSize) {
int totalElnts = (int) page.getTotalElements();
int currentPageNumber = request.getPageNumber();
if (totalElnts == 0) {
List<T> newContent = new ArrayList<T>(0);
PageRequestMobile newRequest = new PageRequestMobile(currentPageNumber, maxPageSize);
return new PageMobile<T>(newContent, newRequest, totalElnts);
}
int nbPages = (int) Math.ceil((double) totalElnts / maxPageSize);
int pageSize = totalElnts / nbPages;
int nbOrphans = totalElnts % nbPages;
if (nbOrphans > 0) {
++pageSize;
}
int startIndex = totalElnts;
int endIndex = totalElnts;
for (int pageNumber = 0; pageNumber <= currentPageNumber; ++pageNumber) {
int currentPageSize = nbOrphans == 0 || pageNumber < nbOrphans ? pageSize : pageSize - 1;
startIndex -= currentPageSize;
endIndex = startIndex + currentPageSize;
}
List<T> newContent = page.getContent().subList(startIndex, endIndex);
PageRequestMobile newRequest = new PageRequestMobile(currentPageNumber, pageSize);
return new PageMobile<T>(newContent, newRequest, totalElnts);
}
// GETTER SETTER
public void setContent(final List<T> content) {
this.content = content;
}
public void setPageable(final PageRequestMobile pageable) {
this.pageable = pageable;
}
public PageRequestMobile getPageable() {
return pageable;
}
public long getTotal() {
return total;
}
public void setTotal(final long total)
{
this.total = total;
}
#Override
public Iterator<T> iterator() {
return this.content.iterator();
}
}
Wrapper to response :
public class Result<T> {
protected Boolean error;
protected String errorMessage;
private HashMap<String, String> errorDetails;
private T objectReceive;
public Result()
{
}
/**
* Initialize with the error at true
*
* #param objectReceive : object to transmit
* #param messageError : message error
*/
public Result(final T objectReceive, final String messageError)
{
this.objectReceive = objectReceive;
hasError(messageError);
}
/**
* Initialize with the error at false
*
* #param objectReceive : object to transmit
*/
public Result(final T objectReceive)
{
this.objectReceive = objectReceive;
this.error = false;
}
public void hasError(final String errorMessage)
{
this.errorDetails = new HashMap<String, String>();
this.error = false;
if (errorMessage != null)
{
this.error = true;
this.errorMessage = errorMessage;
}
}
public Result(final String errorMessage)
{
this.errorDetails = new HashMap<String, String>();
this.error = false;
if (errorMessage != null)
{
this.error = true;
this.errorMessage = errorMessage;
}
}
public Result<T> addDetail(final String name, final String value) {
errorDetails.put(name, value);
return this;
}
public Boolean getError() {
return error;
}
public String getErrorMessage() {
return errorMessage;
}
public HashMap<String, String> getErrorDetails() {
return errorDetails;
}
public void setError(final Boolean error) {
this.error = error;
}
public void setErrorDetails(final HashMap<String, String> errorDetails) {
this.errorDetails = errorDetails;
}
public void setErrorMessage(final String errorMessage) {
this.errorMessage = errorMessage;
}
public T getObjectReceive() {
return objectReceive;
}
public void setObjectReceive(final T objectReceive) {
this.objectReceive = objectReceive;
}
}
With the current version of gwt-jackson (0.6.1), what is sure, you won't be able to use SortMobile as a property in a class. I'll look how I can fix it.
gwt-jackson fails to parse SortMobile because it implements directly Iterable<OrderMobile> and not Iterable<T> with SortMobile<T>.
As a workaround, you have a few solutions :
you can declare the property as a Iterable<OrderMobile> in Page. This way, gwt-jackson will use the serializer/deserializer for Iterable but the instance created by the deserializer will be an ArrayList.
change SortMobile to SortMobile<T extends OrderMobile> implements Iterable<T>
declare your own serializer/deserializer for SortMobile by following the wiki.
Edit :
Since version 0.6.2, you should be able to use SortMobile without compilation error.

Duplicate definition of column 'urbanization' on entity

I'm working with FOSUserBundle and I need to build Users Profile. This is what I did:
Create the User class and extends from BaseUser as FOSUser docs said
namespace Sunahip\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="Profile", mappedBy="user")
*/
protected $profile;
/**
* #ORM\ManyToMany(targetEntity="Sunahip\UserBundle\Entity\Group")
* #ORM\JoinTable(name="fos_user_user_group",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;
}
Create a Profile entity
namespace Sunahip\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* #ORM\Entity
* #ORM\Table(name="profile")
*/
class Profile extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="User", inversedBy="profile")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
/**
* #ORM\Column(name="register_type", type="smallint", length=1)
*/
protected $register_type;
/**
* #ORM\Column(name="rif", type="string", length=25)
*/
protected $rif;
/**
* #ORM\Column(name="ci", type="string", length=25)
*/
protected $ci;
/**
* #ORM\Column(name="firstname", type="string", length=25)
*/
protected $firstname;
/**
* #ORM\Column(name="lastname", type="string", length=25)
*/
protected $lastname;
/**
* #ORM\Column(name="state", type="string", length=150)
*/
protected $state;
/**
* #ORM\Column(name="city", type="string", length=150)
*/
protected $city;
/**
* #ORM\Column(name="town", type="string", length=150)
*/
protected $town;
/**
* #ORM\Column(name="urbanization", type="string", length=150)
*/
protected $urbanization;
/**
* #ORM\Column(name="urbanization", type="string", length=150)
*/
protected $street;
/**
* #ORM\Column(name="aparment", type="string", length=150)
*/
protected $aparment;
/**
* #ORM\Column(name="aparment_no", type="string", length=150)
*/
protected $aparment_no;
/**
* #ORM\Column(name="reference", type="string", length=250)
*/
protected $reference;
/**
* #ORM\Column(name="zipcode", type="string", length=250)
*/
protected $zipcode;
/**
* #ORM\Column(name="fax", type="string", length=250)
*/
protected $fax;
/**
* #ORM\Column(name="local_phone", type="string", length=250)
*/
protected $local_phone;
/**
* #ORM\Column(name="movil_phone", type="string", length=250)
*/
protected $movil_phone;
/**
* #ORM\Column(name="alt_email", type="string", length=250)
*/
protected $alt_email;
/**
* #ORM\Column(name="alt_email", type="string", length=250)
*/
protected $website;
public function getId()
{
return $this->id;
}
public function setUser(User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
public function setRegisterType($register_type)
{
$this->register_type = $register_type;
}
public function getRegisterType()
{
return $this->register_type;
}
public function setRif($rif)
{
$this->rif = $rif;
}
public function getRif()
{
return $this->rif;
}
public function setCI($ci)
{
$this->ci = $ci;
}
public function getCI()
{
return $this->ci;
}
public function setFirstname($firstname)
{
$this->firstname = $firstname;
}
public function getFirstname()
{
return $this->firstname;
}
public function setLastname($lastname)
{
$this->lastname = $lastname;
}
public function getLastname()
{
return $this->lastname;
}
public function setState($state)
{
$this->state = $state;
}
public function getState()
{
return $this->state;
}
public function setCity($city)
{
$this->city = $city;
}
public function getCity()
{
return $this->city;
}
public function setTown($town)
{
$this->town = $town;
}
public function getTown()
{
return $this->town;
}
public function setUrbanization($urbanization)
{
$this->urbanization = $urbanization;
}
public function getUrbanization()
{
return $this->urbanization;
}
public function setStreet($street)
{
$this->street = $street;
}
public function getStreet()
{
return $this->street;
}
public function setAparment($aparment)
{
$this->aparment = $aparment;
}
public function getAparment()
{
return $this->aparment;
}
public function setAparmentNo($aparment_no)
{
$this->aparment_no = $aparment_no;
}
public function getAparmentNo()
{
return $this->aparment_no;
}
public function setReference($reference)
{
$this->reference = $reference;
}
public function getReference()
{
return $this->reference;
}
public function setZipcode($zipcode)
{
$this->zipcode = $zipcode;
}
public function getZipcode()
{
return $this->zipcode;
}
public function setFax($fax)
{
$this->fax = $fax;
}
public function getFax()
{
return $this->fax;
}
public function setLocalPhone($local_phone)
{
$this->local_phone = $local_phone;
}
public function getLocalPhone()
{
return $this->local_phone;
}
public function setMovilPhone($movil_phone)
{
$this->movil_phone = $movil_phone;
}
public function getMovilPhone()
{
return $this->movil_phone;
}
public function setAltEmail($alt_email)
{
$this->alt_email = $alt_email;
}
public function getAltEmail()
{
return $this->alt_email;
}
public function setWebsite($website)
{
$this->website = $website;
}
public function getWebsite()
{
return $this->website;
}
}
Now, I'm trying to validate that entities by running the command doctrine:schema:validate and I get this error:
[Doctrine\ORM\Mapping\MappingException] Duplicate definition of
column 'urbanization' on entity 'Sunahip\UserBundle\Entity\Profile' in
a field or discriminator column mapping.
My questions:
I don't know what is wrong and also don't know what the error means is the first time I got this error.
I don't know if I'm building users profiles in the right way I mean if I should extends from BaseUser or from User
Can I give some help here? Advices? Ideas?
You have (had) basically two probles here:
Duplicated urbanization column name somewhere there which needs to be removed. Only one column with the same name is allowed
Duplicated #ORM\Id annotation in your Profile entity. Remove one from $user because it is not your Id

Doctrine 2 under Zend error: Class Entities\X has no association named Entities\Y

I have a rather strange problem. I'm using Doctrine 2 under Zend Framework 1.11. I have a database called "Sessions", which are training sessions for students. Each session has an associated note, called a SOAPE note. Edit: I am now including both of the entities in question.
Sessions:
use Doctrine\ORM\Mapping as ORM;
/**
* #Entity(repositoryClass="Repositories\Sessions")
* #Table(name="Sessions")
*/
class Sessions
{
/**
* #var integer Id
*
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var integer $schId
*
* #Column(name="schId", type="integer", nullable=false)
*/
protected $schId;
/**
* #var integer $stdId
*
* #Column(name="stdId", type="integer", nullable=false)
*/
protected $stdId;
/**
* #var integer $trainerPsnId
*
* #Column(name="trainerPsnId", type="integer", nullable=false)
*/
protected $trainerPsnId;
/**
* #var boolean $isLegacy
*
* #Column(name="isLegacy", type="boolean", nullable=false)
*/
protected $isLegacy;
/**
* #var float $charge
*
* #Column(name="charge", type="float", nullable=false)
*/
protected $charge;
/**
* #var float $trainerPay
*
* #Column(name="trainerPay", type="float", nullable=false)
*/
protected $trainerPay;
/**
* #var integer $modeId
*
* #Column(name="modeId", type="integer", nullable=false)
*/
protected $modeId;
/**
* #var text $notes
*
* #Column(name="notes", type="text", nullable=true)
*/
protected $notes;
/**
* #var string $twitterNote
*
* #Column(name="twitterNote", type="string", length=20, nullable=true)
*/
protected $twitterNote;
// ASSOCIATIONS
/**
* #OneToOne(targetEntity="Schedule", inversedBy="session")
* #JoinColumn(name="schId", referencedColumnName="id")
*/
protected $schedule;
/**
* #OneToOne(targetEntity="SnSoapeNotes", mappedBy="session")
* #JoinColumn(name="id", referencedColumnName="snId")
*/
protected $soapeNote;
/**
* #ManyToOne(targetEntity="Students")
* #JoinColumn(name="stdId", referencedColumnName="id")
*/
protected $student;
/**
* #ManyToOne(targetEntity="Personnel", inversedBy="sessions")
* #JoinColumn(name="trainerPsnId", referencedColumnName="id")
*/
protected $trainer;
// Getters and Setters
public function getId()
{
return $this->id;
}
public function getSchId()
{
return $this->schId;
}
public function setSchId($schId)
{
$this->schId = $schId;
}
public function getStdId()
{
return $this->stdId;
}
public function setStdId($stdId)
{
$this->stdId = $stdId;
}
public function getTrainerPsnId()
{
return $this->trainerPsnId;
}
public function setTrainerPsnId($trainerPsnId)
{
$this->stdId = $trainerPsnId;
}
public function getIsLegacy()
{
return $this->isLegacy;
}
public function setIsLegacy($isLegacy)
{
$this->isLegacy = $isLegacy;
}
public function getCharge()
{
return $this->charge;
}
public function setCharge($charge)
{
$this->charge = $charge;
}
public function getTrainerPay()
{
return $this->trainerPay;
}
public function setTrainerPay($trainerPay)
{
$this->trainerPay = $trainerPay;
}
public function getModeId()
{
return $this->modeId;
}
public function setModeId($modeId)
{
$this->modeId = $modeId;
}
public function getNotes()
{
return $this->notes;
}
public function setNotes($notes)
{
$this->notes = $notes;
}
public function getTwitterNote()
{
return $this->twitterNote;
}
public function setTwitterNote($twitterNote)
{
$this->twitterNote = $twitterNote;
}
// Foreign Data
public function getSchedule()
{
return $this->schedule;
}
public function getStudent()
{
return $this->student;
}
public function getTrainer()
{
return $this->trainer;
}
public function getSoapeNote()
{
return $this->soapeNote;
}
}
SnSoapeNotes:
namespace Entities;
use Doctrine\Mapping as ORM;
/**
* SnSoapeNotes
*
* #Table(name="SnSoapeNotes")
* #Entity(repositoryClass="Repositories\SnSoapeNotes")
*/
class SnSoapeNotes
{
/**
* #var integer Id
*
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var integer $mental
*
* #Column(name="mental", type="integer", nullable=false)
*/
private $mental;
/**
* #var integer $physical
*
* #Column(name="physical", type="integer", nullable=false)
*/
private $physical;
/**
* #var text $subjective
*
* #Column(name="subjective", type="text", nullable=false)
*/
private $subjective;
/**
* #var text $objective
*
* #Column(name="objective", type="text", nullable=false)
*/
private $objective;
/**
* #var text $plan
*
* #Column(name="plan", type="text", nullable=false)
*/
private $plan;
/**
* #var text $action
*
* #Column(name="action", type="text", nullable=false)
*/
private $action;
/**
* #var text $education
*
* #Column(name="education", type="text", nullable=false)
*/
private $education;
/**
* #var text $warning
*
* #Column(name="warning", type="text", nullable=true)
*/
private $warning;
/**
* #var text $incident
*
* #Column(name="incident", type="text", nullable=true)
*/
private $incident;
/**
* #var text $technical
*
* #Column(name="technical", type="text", nullable=true)
*/
private $technical;
// ASSOCIATIONS
/**
* #Var Sessions $sessions
*
* #Column(name="snId", type="integer", nullable=false)
* #OneToOne(targetEntity="Sessions", inversedBy="soapeNote")
* #JoinColumn(name="snId", referencedColumnName="id")
*/
protected $sessions;
// Getters and Setters
public function getSnId()
{
return $this->snId;
}
public function setSnId($snId)
{
$this->snId = $snId;
}
public function getMental()
{
return $this->mental;
}
public function setMental($mental)
{
$this->mental = $mental;
}
public function getPhysical()
{
return $this->physical;
}
public function setPhysical($physical)
{
$this->physical = $physical;
}
public function getSubjective()
{
return $this->subjective;
}
public function setSubjective($subjective)
{
$this->subjective = $subjective;
}
public function getObjective()
{
return $this->objective;
}
public function setObjective($objective)
{
$this->objective = $objective;
}
public function getPlan()
{
return $this->plan;
}
public function setPlan($plan)
{
$this->plan = $plan;
}
public function getAction()
{
return $this->action;
}
public function setAction($action)
{
$this->action = $action;
}
public function getEducation()
{
return $this->education;
}
public function setEducation($education)
{
$this->education = $education;
}
public function getWarning()
{
return $this->warning;
}
public function setWarning($warning)
{
$this->warning = $warning;
}
public function getIncident()
{
return $this->incident;
}
public function setIncident($incident)
{
$this->incident = $incident;
}
public function getTechnical()
{
return $this->technical;
}
public function setTechnical($technical)
{
$this->technical = $technical;
}
public function getSession()
{
return $this->session;
}
// A quick way to make sure the soape note has been completed.
// Note that objective is left out here because it can be
// filled out beforehand
public function getIsComplete()
{
return !empty($this->subjective)
&& !empty($this->action)
&& !empty($this->plan)
&& !empty($this->education);
}
}
When calling $em->getRepository('Entities\Sessions')->findOneBy('id'), everything works fine--I get the session and its accompanying SOAPE note. Ditto for other associated tables' data.
But now I am trying to write a custom repository to get the notes prior to this session. The function is as follows:
<?php
namespace Repositories;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\DBAL\Types\Type;
/**
* Sessions
*/
class Sessions extends EntityRepository
{
public function getPastSoapeNotes($params) {
$studentId = $params['studentId'];
$latestSession = $params['snDatetime'] ?: date('Y-m-d H:i');
$qb = $this->_em->createQueryBuilder();
$qb->select('n.subjective, n.objective, n.plan, n.action, n.education')
->from('Entities\Sessions', 'sn')
->innerJoin('sn.Entities\SnSoapeNotes', 'n');
return $qb->getQuery()->getResult();
}
}
When I call this, I get the following error:
[Semantical Error] line 0, col 126 near 'n': Error: Class Entities\Sessions has no association named Entities\SnSoapeNotes
I have also tried using the "mappedBy" and "inersedBy" annotations in every possible combination, but to no avail; Doctrine can't seem to find the association. I am at a complete loss as to what is going on.
I figured out what I did wrong. In the join statement, I used 'sn.Entities\SnSoapeNotes' when I should have used just 'soapeNote', which is the property in the Sessions class, not the table name itself.