How to set status for an object - java

I'm developing a simple system for parcel service. I don't fully grasp on how to do this part when setting status of the parcel. When you login you can see all available orders. As a courier you can mark new orders as "accepted" or "rejected". You can mark "accepted" orders as "in transit". And "in transit" orders you can mark as "delivered" or "failed to deliver". My question is do I need to create a field "status" and every time set some kind of string, or I should do a boolean field? By the way, if I would "reject" an order. How could I 'remember' that this particular courier has already rejected that particular oder and do not show it to him? Thank you for your ideas.

Create an Enum and define a variable of that type in your Order object and your business logic should do the setting and interpreting the enum values in your application.
public enum ORDER_STATUS {
ACCEPTED,REJECTED,DELIVERED,FAILED_TO_DELIVER,REJECT;
}
public class Order {
private Long id;
private ORDER_STATUS orderStatus;
}

You can make the enum as an inner static class. Its simpler and faster because you do not have to create an object of ORDER_STATUS.
public class Order {
private final String id;
private final String name;
private final ORDER_STATUS order_status;
public static enum ORDER_STATUS {
ACCEPTED,REJECTED,DELIVERED,FAILED_TO_DELIVER,REJECT;
}
}

Related

Is it possible to build an object like this at runtime in java?

As the title says....
I want to build a POJO with four field variables and at certain runtime events create an instance of this POJO with access to possibly maybe two or three of the fields.
public class Category implements Serializable {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Lets say I create a new Category object but I only want to be able to have access to the name field during runtime. Is there a design pattern I can use to achieve this? I thought about the strategy pattern and looked at the builder but I am still confused if I can do this in java.
Basically the overall goal is to grab an object from a database and return it as a JSON response in jax rs. But sometimes I dont want a complete object returned but only lets say halve of the object to be accessible at during certain runtime events. My apologies if this seems like a dumb question but I know what I want to do but just don't know the best way.
I have the same problem with you, and my project was used springmvc,and the json tool is jackson.With the problem solved, I just use #JsonIgnore.For more details,just read jackson-how-to-prevent-field-serialization
So someone correct me if I am wrong or see a better option than this...with alot of objects this can be alot of extra code for serialization and deserialization...Jackson Provisions is what I need. I can use the annotation #JsonView(DummyClass.class) on the field variable. I will accept this a the best answer in a day or two unless someone else posts a better response.
// View definitions:
class Views {
static class Public { }
static class ExtendedPublic extends PublicView { }
static class Internal extends ExtendedPublicView { }
}
public class Bean {
// Name is public
#JsonView(Views.Public.class) String name;
// Address semi-public
#JsonView(Views.ExtendPublic.class) Address address;
// SSN only for internal usage
#JsonView(Views.Internal.class) SocialSecNumber ssn;
}
With such view definitions, serialization would be done like so:
// short-cut:
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);
// or fully exploded:
objectMapper.getSerializationConfig().setSerializationView(Views.Public.class);
// (note: can also pre-construct config object with 'mapper.copySerializationConfig'; reuse)
objectMapper.writeValue(out, beanInstance); // will use active view set via Config
// or, starting with 1.5, more convenient (ObjectWriter is reusable too)
objectMapper.viewWriter(ViewsPublic.class).writeValue(out, beanInstance);
This information was pulled from http://wiki.fasterxml.com/JacksonJsonViews
with jackson 2.3, I can do this with JAX-RS
public class Resource {
#JsonView(Views.Public.class)
#GET
#Produces(MediaType.APPLICATION_JSON )
public List<Object> getElements() {
...
return someResultList;
}
}

Pattern for persisting data in Realm?

My issue is how to organize the code. Let say I have a User class
public class User extends RealmObject {
#PrimaryKey
private String id;
#Required
private String name;
public User() { // per requirement of no args constructor
id = UUID.randomUUID().toString();
}
// Assume getter & setter below...
}
and a Util class is needed to handles the save in an asynchronous manner since RealmObjects cannot have methods other than getter/setter.
public class Util {
public static void save(User user, Realm realm) {
RealmAsyncTask transaction = realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealm(user); // <====== Argument needs to be declared final in parent method's argument!
}
}, null);
}
}
The intention is to put save() in a Util class to prevent spreading similar save code all over the code-base so that every time I wanted to save I would just call it as such:
User u = new User();
u.setName("Uncle Sam");
Util.save(u, Realm.getDefaultInstance());
Not sure if this affects performance at all, but I was just going to save all fields overwriting what was there except for the unique id field every single time.
The problem is that I now need to set the "user" argument as final in the Util.save() method, which means I cannot pass in the object I need to save other than once.
Is there a different way of handling this? Maybe a different pattern? Or am I looking at this all wrong and should go back to SQLite?
Why is it a problem to set public static void save(final User user, Realm realm) ? It just means you cannot reassign the user variable to something else.
That said, the existence of a save() method can be a potential code smell as you then spread the update behaviour across the code base. I would suggest looking into something like the Repository pattern (http://martinfowler.com/eaaCatalog/repository.html) instead.
Realm is actually working on an example showing how you can combine the Model-View-Presenter architecture with a Repository to encapsulate updates which is a good pattern for what you are trying to do here. You can see the code for it here: https://github.com/realm/realm-java/pull/1960

Play framework 2 (Java) form data binding with nested allowed fields

Consider following model:
public class Contact {
#Required
public String name;
#Valid
public List<Information> informations;
}
public static class Information {
public String securedField;
#Required
public String email;
#Valid
public List<Phone> phones;
public static class Phone {
#Required
#Pattern(value = "[0-9.+]+", message = "A valid phone number is required")
public String number;
}
}
}
I don't want Information securedField to be affected by mass assignment vulnerability. So i decided to set array of allowedFields for Contact Form.
As i know, play forms are based on Spring DataBinder, so is it possible to handle collection fields? I don't want to write smth like:
name
informations[0].email
informations[0].phones*
informations[1].email
informations[1].phones*
etc
Following doesn't work:
name
informations.email
informations.phones*
Should i extend existing Spring DataBinder and Form classes and override bind method in this case?
Here's an arguably simpler solution. How about defining an extra constraint that will trigger a validation failure if the POST data contains any informations[%d].securedField values?
import javax.validation.constraints.Null;
public static class Information {
#Null
public String securedField;
...
}
I think that this way you can call the default bindFromRequest method instead of the one that accepts a whitelist of form field names, and still be protected against a mass assignment attack.
One shortcoming with this approach admittedly is that it would ultimately leak the names of your internal fields in the event of a concerted mass assignment attack. However if they had fairly bland, meaningless names such as securedField (no offence intended!), I'm not sure how this information could be exploited by an attacker.
Edit
If you want to allow assignment to the field based on the current user type, maybe bean validation groups could help:
import javax.validation.constraints.Null;
public class Contact {
public interface Administrator {}
public interface User {}
...
public class Information {
#Null(groups = User.class)
public String securedField;
...
}
}
Controller code
...
final Form<Contact> contactForm;
if (currentUser.isAdministrator()) {
contactForm = form(Contact.class, Administrator.class).bindFromRequest();
} else {
contactForm = form(Contact.class, User.class).bindFromRequest();
}
...
If I understand your question correctly, you can use the following patterns to whitelist nested collection fields:
informations[*].email
informations[*].phones[*].*
i.e.
form.bindFromRequest("name", "informations[*].email", "informations[*].phones[*].*");

ask for suggestions how fields to add to my message class

I'm building an IM program using java IO, and I have an Object called Message.
what field do you recommend me to add to Message Class?
I did the folowing:
public class Message implements Serializable {
static private final long serialVersionUID=12525452;
enum commands{
LEAVE,
ONLINELISTREQUEST,
SENT,
DELIVERED,
READ;
}
enum types{
TEXT,
VEDIO,
PICTURE,
AUDIO,
COMMAND,
//...... what to add??
}
// fields..
private String From;
private String To;
private String Body;
private int type;
private String url;
private int command;
//what to add??
ALso have variable as STATE which will be having values as:-
SEEN, SENT, etc..
This will help in tracking of message and also launch a threads which will keep on checking whether messages which don't have status as SENT/ RECEIVED just resend them
Just use the teachings of Object Oriented concepts. A class should have attributes that are really properties of the entity represented by that class.

Constructor takes two Integers and they must not equal, whats the best way to implement this?

public MyClass(Integer userId, Integer otherId) {
if(!userId.equals(otherId)){
this.userId = userId;
this.otherId = otherId;
}
}
Thats as far as I got, I want to ensure an instance if never created with matching id's ?
If you can't allow the two values to be equal then pretty much your only option it to raise an exception in that case.
I created another method and made the constructor private, it returns null if matching ids
private MyClass(Integer userId, Integer otherId) {
{
this.userId = userId;
this.otherId = otherId;
}
}
public static MyClass getInstance(Integer userId, Integer otherId)
if(!userId.equals(otherId)){
return new MyClass(userId,otherId);
}
return null;
}
I might be completely missing the point of your design, but if you want to create instances of an object with unique ID's that never clash consider using a UUID. Your instances should never have to do a 'circle-jerk' of ID comparisons to make sure none of them are violating the uniqueness constraints.
Documentation on UUID.
I use another approach, I keep a registry of newly created instances (in an HashSet) and allow instatiation of Objects via a static factory.
class User {
private int _id;
private static HashSet _instanced = new HashSet();
public static User getInstance(Integer id) {
if (_instanced.contains(id)) {
return null;
}
return new User(id);
}
private User(Integer id) {
_id = id.toInt();
}
// Getter/Setter for ID
}
Since the constructor is private, none will instantiate another User with the same id.
in your methods you could then write
User x = User.getInstance(1);
Of course this will add one more level to your solution. Still I prefer this kind of approach.

Categories