Solution to implement category in Java - java

You want to create a program for the management of a telephone book.
For each person are provided for the following personal information:
Surname
Name
Title
E-mail address (can not contain spaces and must contain the # symbol)
Company
Position
For every person you can store the following telephone numbers (one for each category)
Home
Office
Mobile Phone.
You can also store a list of other phone numbers. For each of the other numbers, you must store over to the phone number
a description of the number.
Here it is a homework I have to make for this evening in Java.
My issue is how I can implement the various category: Home,Office,ecc...Which is the best solution to implement those category? maybe an enum?
Here it is my implementation:
import java.util.*;
public class Persona {
private String Name;
private String surname;
private String title;
private String mail_addr;
private String company
private String position;
private Phone homePhone;
private Phone officePhone;
private Phone mobilePhone;
private Collection<Phone> otherphonesList
public Persona(String n,String s,String t,String m,String c,String p,Phone hp,Phone of,Phone mp,Collection<Phone> otherphones)
{
name=n;
surname=s;
title=t;
mail_addr=m;
company=c;
position=p;
homePhone=hp;
officePhone=of;
mobilePhone=mp;
otherphonesList=new ArrayList<Phone>(otherphones);
}
public String getName()
{
return name;
}
public String getSurname()
{
return surname;
}
public String getTitle()
{
return title;
}
public String getMail()
{
return mail_addr;
}
public String getCompany()
{
return company;
}
public String getPosition()
{
return position;
}
}
public class Phone {
private String phone;
private String description;
public Phone(String phone,String description)
{
this.phone=phone;
this.description=description;
}
public String getPhone()
{
return phone;
}
public String getDescription()
{
return description;
}
}

You can write a PhoneBook class with fields you need:
public class PhoneBook {
private Phone homePhone;
private Phone officePhone;
private Phone mobilePhone;
private List<Phone> otherPhones;
..getters/setters..
}
public class Phone {
private String phone;
private String description;
..getters/setters..
}

enums are a good solution if:
The number of items is fixed
All the information of the item is fixed as well (no loading of external files/resources/etc).
In a real application, you probably need to display the category on a display. This includes translating the category into the user's language which means there is an external dependency.
In such a case, you would use the enum as a key for a factory that gives you the text for each entry in the enum. The factory decouples your constant enum from the variables in the real world (like different/changing translations in the UI).

You may have a look at the Map class to store the phone numbers and add accessors for home, office and mobile phone entries.

Related

How do you create Collections in Brightspot CMS using Java classes with the Dari framework?

import com.psddev.cms.db.Content;
import com.psddev.dari.db.Recordable;
public class MattContent extends Content {
private String tt;
private String uu;
public String getUu() {
return uu;
}
public MattContent setUu(String uu) {
this.uu = uu;
return this;
}
public String getTt() {
return tt;
}
public MattContent setTt(String tt) {
this.tt = tt;
return this;
}
#Recordable.DisplayName("Headline")
private String title;
#Recordable.DisplayName("Fields")
private String fields;
#Recordable.Regex(value=".+\\#.+\\..+", validationMessage="Use email format 'myemail#address.com'")
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
The code above renders individual fields in the UI from a Java class using the Dari framework in Brightspot CMS. I would like to do more than individual fields, but Collections as well.
I can see how to set up a Collection for users in the docs:
https://docs.brightspot.com/4.0/en/plugins-guide/collections/creating-collections.html
However, I cannot find the annotation in Dari to set this up for devs:
https://docs.brightspot.com/4.2/en/dari-guide/data-modeling/data-modeling-annotations.html
I'd really appreciate any help in pointing me to the right section of the documentation. This may be a vocabulary issue -- I may not be typing in the right words to get this information.
*"Cluster" isn't yielding the results I'm looking for either.
Thanks for your time and help.
Solution: There is no annotation needed for a collection. One can write a simple set or list:
private Set<Internal> internalSet;
private List<Internal> internalList;
The solution is so simple, I overlooked the obvious: annotations are extras in Dari, not essential for rendering content to Brightspot CMS' UI.

vavr add nested validations with validations combine

I have an input object as
class Person {
private String name;
private String email;
private String phone;
private Address address;
public static class Address {
private String city;
private String pincode;
private String street;
private AddrDetails details;
public static class AddrDetails {
private String state;
private String country;
}
}
}
I am using vavr Validations to validate the input
public static Validation<Seq<ConstraintViolation>, PersonDetailsModel> validatePerson(PersonDetailsRequest request) {
Validation
.combine(
validateName("name", request.getName()),
validateEmail("email", request.getEmail()),
validatePhone("phone", request.getPhone()),
validateAddress(request.getAddress())
).ap((name, email, phone, address) -> new PersonDetailsModel(name, email, phone, address);
}
public static Validation<Seq<ConstraintViolation>, Person.Address> validateAddress(
Person.Address request) {
return Validation
.combine(..
).ap((..) -> new Person.Address(..);
}
In the second function, it returns Seq of ConstraintViolation while validatePerson expects only ConstraintViolation which is why it is failing although I have to add one more level of nesting of validations for AddrDetails. How to handle nested objects validations with this approach.
I am not sure about how shall I go ahead?
In our project we call .mapError(Util::flattenErrors) after .ap. I have the feeling that there is a better way, but this at least solves the nesting.
The method in the Util class looks like this :
public static Seq<ConstraintViolation> flattenErrors(final Seq<Seq<ConstraintViolation>> nested) {
return nested
.flatMap(Function.identity())
.distinct(); // duplicate removal
}

Gson - Read a value with two different keys

In my Android project I have two types of response where both response are identical except two keys.
Response 1
{"fullName":"William Sherlock Scott Holmes","address":"221B Baker Street, London, England, UK","downloads":642,"rating":3,"repos":["https://link1","https://link2","https://link3"]}
Response 2
{"name":"Sherlock","city":"London","downloads":642,"rating":3,"repos":["https://link1","https://link2","https://link3"]}
If you see the responses only two key names are changing fullName/name and address/city
I don't want to create one more pojo for other response. My question is: is it possible to use only one Pojo to read both responses?
public class AccountInfo {
private String name;
private String city;
//other objects
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
//other setters and getters
}
Any help will be appreciated...
You can annotate the members to accept values from two different json names using the #SerializedName annotation:
#SerializedName(value = "name", alternate = {"fullName"})
private String name;
#SerializedName(value = "city", alternate = {"address"})
private String city;
Either named element can then be placed into the members that are annotated like this.
UPDATED :
#SerializedName alternate names when deserializing is added in Version 2.4
Yes, you can totally use one POJO class for deserializing both responses. Your POJO class will contain keys from both responses.
public class Response {
private String name;
private String city;
private String fullName;
private String address;
private Integer downloads;
private Integer rating;
private List<String> repos ;
}
But when using the Response class, be careful that for first response, the name and city will be null, and for the second one, the address and fullname.
Yeah you can do that in a single POJO. Try this:
public class POJO {
#SerializedName("name")
public String name;
#SerializedName("city")
public String city;
#SerializedName("fullName")
public String fullName;
#SerializedName("address")
public String address;
#SerializedName("downloads")
public Integer downloads;
#SerializedName("rating")
public Integer rating;
#SerializedName("repos")
public List<String> repos = new ArrayList<String>();
}
While parsing you have to check values for null. For eg -
While Parsing Response 1: name and city variables will be null
While Parsing Response 2: fullname and address will be null
Note : Try checking values for null before using else you'll get nullpointerexception
Define all possible fields in your POJO Class like
public class AccountInfo {
private String name;
private String city;
private String fullname;
private String address;
}
While performing operation check for null in those feilds

What GSON deserializers do I need?

Evening,
I retrieve JSON data from a server in this format:
Json-Book:
{
_id: String,
isbn: String,
owner: String username,
rentedTo: Array[String usernames]
}
Json-Crowd:
{
_id: String,
isbn: String,
owner: String username,
availableForRent: Integer,
rentedTo: Array[String usernames]
}
Json-User:
{
username: String,
books: Array[Book],
crowds: Array[Crowd]
}
Similarly, I have three classes:
public class Book{
private String _id;
private String isbn;
private User owner;
private ArrayList<User> rentedTo;
public Book(String _id, String isbn, User owner, ArrayList<User> rentedTo) {
this._id = _id;
this.isbn = isbn;
this.owner = owner;
this.rentedTo = rentedTo;
}
}
public class Crowd {
private String _id;
private String name;
private User owner;
private ArrayList<User> members;
public Crowd(String _id, String name, User owner, ArrayList<User> members) {
this._id = _id;
this.name = name;
this.owner = owner;
this.members = members;
}
}
public class User {
private String name;
private Shelf shelf;
private ArrayList<Book> books;
private ArrayList<Crowd> crowds;
public User(String name, ArrayList<Book> books, ArrayList<Crowd> crowds) {
this.name = name;
this.booksOwned = books;
this.crowds = crowds;
}
}
As you can see, all the field names match up, but not all of the types. Users in the keys owner and rentedTo in Json-book and Json-crowd have values of type String and ArrayList<String> respectively, where the strings are unique usernames. In the classes, these fields are of type User and ArrayList<User>. In and of itself, this is no problem, because I can get the User object from the string with this method:
public User getUser(String username) {
return users.get(username);
}
Now, I'm a bit confused as to what deserializers I need in order to get proper objects from the JSON data. How would the, uh, architecture of this look? Deserializers for each class Book, Crowd and User, each of which fetches one field at a time from the Json-data and calls the constructor?
I can't wrap my head around how this would work together. The deserializer for User would need to use/reference the deserializer for Crowd, but do I another deserializer since the objects are in array?
I assume I would need an opposite set of serializers in order to get the classes into Json-data of the correct format.

Java Enum with space and shortcode value

I have a enum in which I need to set the country in the web page.
Similar to this page - Java enum elements with spaces?
// sample
INDIA("India"),
RUSSIA("Russia"),
NORTH_AMERICA("North America");
I want the user to see "North America" in the dropdown.
But I need to pass "NA" to the database.
I tried the following. But getting the shortcode(IND,RUS,NA) in the dropdown.
IND("India"),
RUS("Russia"),
NA("North America");
Can anyone please help me in fixing this?
You can have an enum like this, where you use the name when displaying it in dropdown and the code, when passing to the DB.
enum Country {
INDIA("India", "IND"), RUSSIA("Russia", "RUS"), NORTH_AMERICA(
"North America", "NA");
private String name;
private String code;
Country(String name, String code) {
this.name = name;
this.code = code;
}
// Getters and other methods for name and code
}
you should try with variables inside the enum.
So your enum should be like this
public enum Country {
INDIA("India","IND"),
RUSSIA("Russia","RUS"),
NORTH_AMERICA("North America","NA");
private String country;
private String shortCode;
private Country(String country, String shortCode) {
this.country = country;
this.shortCode = shortCode;
}
public String getCountry() {
return country;
}
public String getShortCode() {
return shortCode;
}
}

Categories