This is my object :
public class ObjectsInGroupRealm extends RealmObject {
#PrimaryKey
private Long id;
private String name;
private String groupName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
And when I create a new object I want to check if object is exist this same name and this same groupName . A object name could be in few groups. This is my code how I save a objects :
public static void saveObjectsInGroup(ArrayList<String> objects, String groupName , Realm realm){
for(String object : objects){
ObjectsInGroupRealm objectsInGroupRealm = new ObjectsInGroupRealm();
Long key;
try {
key = (Long) realm.where(ObjectsInGroupRealm.class).max("id") + 1;
} catch (NullPointerException ex) {
key = 0L; // when there is no object in the database yet
}
objectsInGroupRealm.setId(key);
objectsInGroupRealm.setName(object);
objectsInGroupRealm.setGroupName(groupName);
realm.beginTransaction();
realm.copyToRealm(objectsInGroupRealm);
realm.commitTransaction();
}
}
So the easiest way is doing a query and checking if the returned Object is null:
ObjectsInGroupRealm object = realm.where(ObjectsInGroupRealm.class)
.equalTo("name", name)
.equalTo("groupName", groupName)
.findFirst();
if(object == null){
//add new object
} else {
//handle object already existing
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
[UML Diagram][1]
I'm studying for the midterm exam next week and I'm practicing some given examples from my professor; however, I am having some trouble with class return type methods.
I attached UML diagram just in case.
What i'm trying to understand is getPerson method in Job class. I don't think i need a array list in Job class to store all the employee. Because I have an array list already in Company class. Also return type is Employee class that I'm not sure how to get person's info using this class return type.
My problems
public Employee getPerson() {} in Job class
public boolean isVacant() {} in Job class
Also would you mind checking getVacantJobs, getFilledJobs, and getAllJobs methods if those are correctly built?
I used iterator to display all the stored jobs.
---------------------------Employee Class -----------------------------
public class Employee {
private String name;
private int id;
public Employee(int id, String name) {
this.name = name;
this.id =id;
}
public final String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
public final int getId() {
return id;
}
public final void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + "]";
}
}
----------------------------Job Class--------------------------------------
public class Job {
private String description;
private int id;
private double maxSalary;
public Job(int id, double maxSalary, String description) {
this.description = description;
this.id = id;
this.maxSalary = maxSalary;
}
public Job(int id, double maxSalary, String description, Employee e1) {
this.description = description;
this.id = id;
this.maxSalary = maxSalary;
}
#Override
public String toString() {
return "Job [description=" + description + ", id=" + id
+ ", maxSalary=" + maxSalary + "]";
}
public final String getDescription() {
return description;
}
public final void setDescription(String description) {
this.description = description;
}
public final double getMaxSalary() {
return maxSalary;
}
public final void setMaxSalary(double maxSalary) {
this.maxSalary = maxSalary;
}
public final int getId() {
return id;
}
public Employee getPerson() {
retrun
}
public final void setPerson(Employee person) {
this.id = person.getId();
}
}
--------------------------Company Class ---------------------------
import java.util.ArrayList;
import java.util.Iterator;
public class Company {
static ArrayList list = new ArrayList();
Iterator itr = list.iterator();
private String name;
public Company(String name) {
this.name = name;
}
public Company() {
// TODO Auto-generated constructor stub
}
public static void addJob(Job j1) {
list.add(j1);
}
public void removeJob(int id) {
list.remove(id);
}
public ArrayList<Job> getVacantJobs() {
while (itr.hasNext()) {
if ((itr == null)) {
System.out.println(itr);
}
}
return null;
}
public ArrayList<Job> getFilledJobs() {
while (itr.hasNext()) {
if (!(itr == null)) {
System.out.println(itr);
}
}
return null;
}
public ArrayList<Job> getAllJobs() {
while (itr.hasNext()) {
System.out.println(itr.next());
}
return null;
}
}
Add field person to Job class.
public class Job {
// .....
private Employee person;
public Employee getPerson() {
return person;
}
public final void setPerson(Employee person) {
this.person = person;
}
public boolean isVacant() {
return person == null;
}
}
And add jobs field to Company class.
public class Company {
// static ArrayList list = new ArrayList(); // You don't need this
// Iterator itr = list.iterator(); // You don't need this.
// .....
private ArrayList<Job> jobs = new ArrayList<>();
public ArrayList<Job> getVacantJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
if (job.isVacant())
result.add(job);
return result;
}
public ArrayList<Job> getFilledJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
if (!job.isVacant())
result.add(job);
return result;
}
public ArrayList<Job> getAllJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
result.add(job);
return result;
}
}
I have the following advice code:
#Around("annotatedMethod()")
public Object aroundGetPanel(ProceedingJoinPoint joinPoint) throws Throwable
{
Object result = joinPoint.proceed();
return result;
}
And the method who executes the above method is:
public Person getPerson(String id){
return new Person(1,"Maialen");
}
public class Person {
private Integer id = null;
private String name = null;
public Person(Integer id,String name){
this.setId(id);
this.setName(name);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return nombre;
}
public void setName(String name) {
this.name = name;
}
}
How can I get the params of object result (Person)?
Using reflection? Using annotations?
I discovered how to do it via reflection:
Class<?> clazz = result.getClass();
Field field = org.springframework.util.ReflectionUtils.findField(clazz, "name");
org.springframework.util.ReflectionUtils.makeAccessible(field);
String name=field.get(result).toString();
But I prefer do it by annotations. Is there a mode?
I want update only not null field. I have some class like below
#DatabaseTable
public class ClickCount implements Serializable {
private static final long serialVersionUID = -6582623980712135028L;
public static final String DATE_FIELD_NAME = "lastClickDate";
#DatabaseField(generatedId = true)
private Integer id;
#DatabaseField(columnName = DATE_FIELD_NAME)
private Date lastClickDate;
#DatabaseField(index = true)
private String name;
#DatabaseField
private String description;
#DatabaseField
private int value;
#DatabaseField(canBeNull = true, foreign = true)
private ClickGroup group;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public ClickGroup getGroup() {
return group;
}
public void setGroup(ClickGroup group) {
this.group = group;
}
public Date getLastClickDate() {
return lastClickDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
/**
* This updates the value and adjusts the date.
*/
public void changeValue(int value) {
this.value = value;
this.lastClickDate = new Date();
}
#Override
public String toString() {
return name + " " + value;
}
}
I get some json and parse with ClickCount class, but some field may be null. When I update data in DB null field writing into DB. How write only not null field?
Updating data below
Dao<ClickCount, Integer> dao = getHelper().getClickDao();
ClickCount clickCountInDb = dao.queryForAll().get(0);
ClickCount clickCountFromServer = getFromServer();
clickCountFromServer.setId(clickCountInDb.getId());
dao.update(clickCountFromServer);
You have update each field manually after checking if its null or not. After that just update your fetched entity like this:
Dao<ClickCount, Integer> dao = getHelper().getClickDao();
ClickCount clickCountFromServer = getFromServer();
ClickCount clickCountInDb = dao.queryForId(clickCountInDb.getId()); // query for specific item. After this you should check if the query was succesful.
if (clickCountFromServer.getLastClickDate() != null)
{
clickCountInDb.setLastClickDate(clickCountFromServer.getLastClickDate());
}
if (clickCountFromServer.getName() != null)
{
clickCountInDb.setName(clickCountFromServer.getName());
}
// and so on for all fields
// after you set not null properties on the object clickCountInDb you have to propagate changes back to the database:
dao.update(clickCountInDb);
Normally if we want to initialize a generic non-primitive ArrayList we do this
ArrayList<?> arrayList = new ArrayList<MyClass.class>();
But I want to do something similar to this no matter which class object I pass, i.e
private void getModel(Class responseType){
//Something similar, because this does not work..
ArrayList<?> arrayList = new ArrayList<responseType>();
}
Any Help would be greatly appreciated.
Try something like this
private <T> void setModel(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
}
If you want to get the list back then
private <T> ArrayList<T> getModel(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
EDIT
A FULL EXAMPLE SHOWING HOW TO USE GENERIC TYPE FOR ARRAYLIST
Tester class with main method and the generic Method
public class Tester {
private <T> ArrayList<T> getModels(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
public static void main(String[] args) {
Data data = new Data(12, "test_12");
Magic magic = new Magic(123, "test_123");
Tester t = new Tester();
ArrayList<Data> datas = (ArrayList<Data>) t.getModels(Data.class);
datas.add(data);
for(Data data2 : datas) {
System.out.println(data2);
}
ArrayList<Magic> magics = (ArrayList<Magic>) t.getModels(Magic.class);
magics.add(magic);
for(Magic magic2 : magics) {
System.out.println(magic2);
}
}
}
Another possibility to use the same things without parameter since we don't use it inside the method
public class Tester {
private <T> ArrayList<T> getModel() {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
public static void main(String[] args) {
Data data = new Data(12, "test_12");
Magic magic = new Magic(123, "test_123");
Tester t = new Tester();
ArrayList<Data> datas = t.getModel();
datas.add(data);
for(Data data2 : datas) {
System.out.println(data2);
}
ArrayList<Magic> magics = t.getModel();
magics.add(magic);
for(Magic magic2 : magics) {
System.out.println(magic2);
}
}
}
Model class (Data)
public class Data {
private Integer id;
private String name;
public Data() {
}
public Data(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
}
}
Model class (Magic)
public class Magic {
private Integer id;
private String name;
public Magic() {
}
public Magic(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
}
}
This works:
private void getModel(){
ArrayList<?> arrayList = new ArrayList<Object>();
}
I mean, it is unclear what you are trying to do. Generics is purely compile-timem, to perform compile-time type checking. Therefore, if the type parameter is not known at compile time, it would be useless.
Try using following
public <T> List<T> getList(Class<T> requiredType) {
return new ArrayList<T>();
}
public void useList() {
List<Integer> ints = getList(Integer.class);
List<String> lists = getList(String.class);
}
I want to use javax.ws.rs.core.Response to send and receive an Card entity object. But I don't know how to convert the contents back in to a Card object.
My testCreate() method should execute the create(Card card) method, receive back the json and convert it in to a card object. But I somehow always get type mismatches or it says that the getEntity() method can't be executed like this: response.getEntity(Card.class).
Does anybody know how I have to handle the response correctly so that I can convert the returned json entity in to a Card object again?
Here my CardResource method:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response create(Card card) {
Card c = dao.create(card);
if(c.equals(null)) {
return Response.status(Status.BAD_REQUEST).entity("Create failed!").build();
}
return Response.status(Status.OK)
.entity(c)
.type(MediaType.APPLICATION_JSON)
.build();
}
And here my CardResourceTests class
#Test
public void testCreate() {
boolean thrown = false;
CardResource resource = new CardResource();
Card c = new Card(1, "Cardname", "12345678", 1, 1,
"cardname.jpg", new Date(), new Date());
try {
Response result = resource.create(c);
System.out.println(result.getEntity(Card.class)); // not working!!!
if(result.getStatus() != 200) {
thrown = true;
}
} catch(Exception e) {
e.printStackTrace();
thrown = true;
}
assertEquals("Result", false, thrown);
}
And here my Card.class
#XmlRootElement
#PersistenceCapable(detachable="true")
public class Card {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private Integer id;
#Persistent
private String name;
#Persistent
private String code;
#Persistent
private Integer cardProviderId;
#Persistent
private Integer codeTypeId;
#Persistent
private String picturePath;
#Persistent
private Boolean valid;
#Persistent
private Date mobCreationDate;
#Persistent
private Date mobModificationDate;
#Persistent
private Date creationDate;
#Persistent
private Date modificationDate;
public Card() {
this.setId(null);
this.setName(null);
this.setCode(null);
this.setCardProviderId(null);
this.setCodeTypeId(null);
this.setPicturePath(null);
this.setMobCreationDate(null);
this.setMobModificationDate(null);
this.setCreationDate(null);
this.setModificationDate(null);
}
public Card(Integer id, String name, String code, Integer cardProviderId,
Integer codeTypeId, String picturePath,
Date mobCreationDate, Date mobModificationDate) {
this.setId(id);
this.setName(name);
this.setCode(code);
this.setCardProviderId(cardProviderId);
this.setCodeTypeId(codeTypeId);
this.setPicturePath(picturePath);
this.setMobCreationDate(mobCreationDate);
this.setMobModificationDate(mobModificationDate);
this.setCreationDate(new Date());
this.setModificationDate(new Date());
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public Integer getCardProviderId() {
return cardProviderId;
}
public void setCardProviderId(Integer cardProviderId) {
this.cardProviderId = cardProviderId;
}
public void setCode(String code) {
this.code = code;
}
public Integer getCodeTypeId() {
return codeTypeId;
}
public void setCodeTypeId(Integer codeTypeId) {
this.codeTypeId = codeTypeId;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public Date getMobCreationDate() {
return mobCreationDate;
}
public void setMobCreationDate(Date mobCreationDate) {
this.mobCreationDate = mobCreationDate;
}
public Date getMobModificationDate() {
return mobModificationDate;
}
public void setMobModificationDate(Date mobModificationDate) {
this.mobModificationDate = mobModificationDate;
}
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
}
And here my CardDAO class
public class CardDAO {
private final static Logger logger = Logger.getLogger(CardDAO.class.getName());
public Card create(Card card) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Card c = new Card(card.getId(), card.getName(), card.getCode(),
card.getCardProviderId(), card.getCodeTypeId(), card.getPicturePath(),
new Date(), new Date());
try {
pm.makePersistent(c);
} catch(Exception e) {
logger.severe("Create failed: " + e.getMessage());
return null;
} finally {
pm.close();
}
return c;
}
}
Is your Card class using #XmlRootElement and #XmlElement annotations to enable JAXB mapping JSON to/from POJO?
See example:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Book {
#XmlElement(name = "id")
String id;
//...
I am not sure that it is correct to call the annotated web-service method just like a simple method with params. Try to remove all annotations from your CardResource class and invoke this method simply like a class method.