I have the following enum created in groovy:
enum Status {
FAILED(0, "Failed"),
SUCCESSFUL(1, "Successful")
private final int key
private final String val
public Status(int key, String val) {
this.val = val
this.key = key
}
String toString() { return val }
}
I would like to write a function to search the entries of my enum class that returns true of Status.contains("Failed"). Is it possible to do this?
In Groovy, you could do:
enum Status {
FAILED(0, 'Failed'),
SUCCESSFUL(1, 'Successful')
private final int key
private final String val
public Status(int key, String val) {
this.val = val
this.key = key
}
String toString() { val }
static boolean containsVal(String val) {
Status.values()*.val.contains val
}
}
assert Status.containsVal('Failed')
You can write necessary methods yourself
Here is an example in java:
enum Status {
FAILED(0, "Failed"),
SUCCESSFUL(1, "Successful");
private final int key;
private final String val;
Status(int key, String val) {
this.val = val;
this.key = key;
}
public static Status containsName(String name) {
for (Status status : Status.values()) {
if (status.name().equalsIgnoreCase(name)) {
return status;
}
}
return null;
}
public static Status containsVal(String val) {
for (Status status : Status.values()) {
if (status.val.equalsIgnoreCase(val)) {
return status;
}
}
return null;
}
public String toString() { return val; }
}
Method containsName returns a Status instance if its name equals to an argument. Method containsValue returns a Status instance if its value equals to an argument.
Status failed = Status.containsName("FAILED");
Status successful = Status.containsVal("Successful");
Related
Now I have a simple enum called AppName:
package misc.enumn.app;
import lombok.Getter;
import misc.enumn.BaseEnum;
/**
* #author dolphin
*/
#Getter
public enum AppName implements BaseEnum {
CRUISE( 1, "cruise"),
BACK(2, "back"),
;
private Integer key;
private String value;
AppName(Integer key, String value) {
this.key = key;
this.value = value;
}
public void setKey(Integer key) {
this.key = key;
}
public void setValue(String value) {
this.value = value;
}
public static AppName getAppMarkByValue(String value) {
AppName datetimeType = null;
for (AppName type : AppName.values()) {
if (type.name().equals(value)) {
datetimeType = type;
}
}
return datetimeType;
}
public static AppName getAppMarkByKey(Short key) {
AppName datetimeType = null;
for (AppName type : AppName.values()) {
if (type.key.equals(key)) {
datetimeType = type;
}
}
return datetimeType;
}
}
then I define a request object like this:
#Data
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserLoginRequest implements Serializable {
#ApiModelProperty(value = "app")
private AppName app;
}
when I passed appId 1 to the server side, the server parsed AppName as BACK, I do not understand why it parsed as the BACK not 'CRUISE'? I have already define the enum parser:
public class IntegerCodeToEnumConverterFactory implements ConverterFactory<Integer, BaseEnum> {
private static final Map<Class, Converter> CONVERTERS = Maps.newHashMap();
#Override
public <T extends BaseEnum> Converter<Integer, T> getConverter(Class<T> targetType) {
Converter<Integer, T> converter = CONVERTERS.get(targetType);
if (converter == null) {
converter = new IntegerToEnumConverter<>(targetType);
CONVERTERS.put(targetType, converter);
}
return converter;
}
}
and add to interceptor config:
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(new IntegerCodeToEnumConverterFactory());
}
but seem still could not parse the enum, what should I do to make it parse the app correctly? this is the wrong parse(I want 1 parsed as CRUISE and 2 parsed as BACK):
By the way, when I replace the app from enum as Integer, it could parse it correctly(receive value 1). But I think using enum may be better for readable.
public class IntegerToEnumConverter <T extends BaseEnum> implements Converter<Integer, T> {
private Map<Integer, T> enumMap = Maps.newHashMap();
public IntegerToEnumConverter(Class<T> enumType) {
T[] enums = enumType.getEnumConstants();
for (T e : enums) {
enumMap.put(e.getKey(), e);
}
}
#Override
public T convert(Integer source) {
T t = enumMap.get(source);
if (ObjectUtils.isNull(t)) {
throw new IllegalArgumentException("");
}
return t;
}
}
what I am doing only support http get method, if you want to parse enum in http post method. define the code like this:
#JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static AppName resolve(Integer key) {
return mappings.get(key);
}
this is my full code:
#Getter
public enum AppName implements BaseEnum {
CRUISE(1, "cruise"),
BACK(2, "back"),
;
#JsonValue
private Integer key;
private String value;
AppName(Integer key, String value) {
this.key = key;
this.value = value;
}
private static final Map<Integer, AppName> mappings;
static {
Map<Integer, AppName> temp = new HashMap<>();
for (AppName courseType : values()) {
temp.put(courseType.key, courseType);
}
mappings = Collections.unmodifiableMap(temp);
}
#EnumConvertMethod
#JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static AppName resolve(Integer key) {
return mappings.get(key);
}
public void setKey(Integer key) {
this.key = key;
}
public void setValue(String value) {
this.value = value;
}
public static AppName getAppMarkByValue(String value) {
AppName datetimeType = null;
for (AppName type : AppName.values()) {
if (type.name().equals(value)) {
datetimeType = type;
}
}
return datetimeType;
}
public static AppName getAppMarkByKey(Short key) {
AppName datetimeType = null;
for (AppName type : AppName.values()) {
if (type.key.equals(key)) {
datetimeType = type;
}
}
return datetimeType;
}
}
How can I add some description to each enum value for swagger-UI documentation?
My EnumClass:
#ApiModel
public enum EnumCarrierSelectionSubstitutionInformation {
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_1(1), //
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_2(2), //
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_3(3), //
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_4(4), //
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_5(5), //
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_6(6), //
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_7(7);
private int numVal;
EnumCarrierSelectionSubstitutionInformation(int numVal) {
this.numVal = numVal;
}
public int getNumVal() {
return numVal;
}
}
The model
private EnumCarrierSelectionSubstitutionInformation carrierSelectionSubstitutionInformation;
// getter setter......
I would like to add some description to CARRIER_SELECTION_SUBSTITUTION_INFORMATION_1.
I tried
#ApiModelProperty(value = "blabla2")
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_1(1), //
but that is not working.
Swagger-UI output:
carrierSelectionSubstitutionInformation (string, optional) = ['CARRIER_SELECTION_SUBSTITUTION_INFORMATION_1', 'CARRIER_SELECTION_SUBSTITUTION_INFORMATION_2', 'CARRIER_SELECTION_SUBSTITUTION_INFORMATION_3', 'CARRIER_SELECTION_SUBSTITUTION_INFORMATION_4', 'CARRIER_SELECTION_SUBSTITUTION_INFORMATION_5', 'CARRIER_SELECTION_SUBSTITUTION_INFORMATION_6', 'CARRIER_SELECTION_SUBSTITUTION_INFORMATION_7']
string
Enum: "CARRIER_SELECTION_SUBSTITUTION_INFORMATION_1", "CARRIER_SELECTION_SUBSTITUTION_INFORMATION_2", "CARRIER_SELECTION_SUBSTITUTION_INFORMATION_3", "CARRIER_SELECTION_SUBSTITUTION_INFORMATION_4", "CARRIER_SELECTION_SUBSTITUTION_INFORMATION_5", "CARRIER_SELECTION_SUBSTITUTION_INFORMATION_6", "CARRIER_SELECTION_SUBSTITUTION_INFORMATION_7"
How can I do that?
public class Enum {
public enum EnumCarrierSelectionSubstitutionInformation {
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_1(1,"ONE"), //
CARRIER_SELECTION_SUBSTITUTION_INFORMATION_2(2,"TWO"),
private final int value;
private final String description;
EnumCarrierSelectionSubstitutionInformation(int value, String desc){
this.value = value;
this.description = desc;
}
public int value(){
return this.value;
}
public String description(){
return this.description;
}
}
public static void main(String[] args){
for (EnumCarrierSelectionSubstitutionInformation elem: EnumCarrierSelectionSubstitutionInformation.values()){
System.out.println(elem + "value is "+ new Integer(elem.value()) + " desc is " + elem.description());
}
}
}
I am using a custom class object as the key for a HashMap. In this class definition, I have overridden the equals() and hashCode() methods.
public class TimeTableDataModel {
Map <Course, List <Timings>> tm;
TimeTableDataModel() {
tm = new HashMap<>();
}
void addCourseItem(Course course) {
tm.put(course, new ArrayList<Timings>());
}
void addNewTimeTableItem(Course course, Timings newTiming) {
List <Timings> t;
if(!tm.containsKey(course)) {
addCourseItem(course);
}
t = tm.get(course);
t.add(newTiming);
tm.put(course, t);
}
public static final class Course {
private final String courseCode;
private final String courseName;
private final String section;
private final String group;
Course(String code, String courseName, String section, String group) {
this.courseCode = code;
this.courseName = courseName;
this.section = section;
this.group = group;
}
public String getCourseCode() { return courseCode; }
public String getCourseName() { return courseName; }
public String getSection() { return section; }
public String getGroup() { return group; }
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Course)) {
return false;
}
Course otherObj = (Course) obj;
return Objects.equals(courseCode,otherObj.courseCode)
&& Objects.equals(courseName, otherObj.courseName)
&& Objects.equals(section, otherObj.section)
&& Objects.equals(group, otherObj.group);
}
#Override
public int hashCode() {
return Objects.hash(courseCode, courseName, section, group);
}
}
public static class Timings {
String time;
String day;
String room;
Timings(String time, String day) {
setTime(time);
setDay(day);
}
public String getTime() { return time; }
public String getday() { return day; }
public void setTime(String time) { this.time = time; }
public void setDay(String day){this.day = day;}
}
}
In above code I have created Course class to be used as the key for the HashMap and using a List<Timings> for values. What I intend is to get a List of timings when a Course is passed to hm.get(course). So far I can get a keyset then sequentially get values for each course.
for(Course c : timetable.tm.keySet()) {
System.out.println(c.getCourseCode() + " " + c.getCourseName());
for(Timings t : timetable.tm.get(c)) {
System.out.println(t.time + " " +t.room + " "+ t.day);
}
};
Here's the code that populates the HashMap
static TimeTableDataModel timetable = new TimeTableDataModel();
Course course = new Course(courseCode,null,section,group);
Timings dt = new Timings(time, getDayOfWeek(i));
dt.room = roomNo;
timetable.addNewTimeTableItem(course, dt);
So to get the timings for a particular course I have to traverse the whole HashMap until the desired course Key is found. What I want is a way to distinguish between each course object contained in the HashMap Key, so I can get Timings for any random course without traversing the whole KeySet.
Thanks in advance. Please ask if somethings is unclear in code
Problem what I see here is
if(!tm.containsKey(course)){
addCourseItem(course);
}
and
if (this == obj) {
return true;
}
because you are comparing the object. Since both are same class objects equals will always return true and map concludes it as duplicate key.
I have a javascript array containing an object which represents a key value pair. I'm trying to convert this javascript object into a java object. Could someone assist me? Thanks in advance.
Javascript
var array = [];
for (var i = 0; i < filterIdArray.length; i++) {
array.push({name:filterIdArray[i], value:$("#" + filterIdArray[i]).val()});
}
params["t:array"] = array;
Java
#RequestParameter(value = "t:array", allowBlank = true) String array
List<String> inputs = null;
if(array != null) {
inputs = Arrays.asList(array);
}
Java Object representing key value pair
public class Test {
private String name;
private String value;
public Test() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public enum Code {
E1330("MERCOSUR (SOUTH AMERICAN COMMON MARKET)"),
E0257("Guinea Biss."),
E0252("Gambia");
private Code(String value){
setStringValue(value);
}
private Code (int value) {
setIntValue(value);
}
private int intValue;
private String stringValue;
public String getStringValue() {
return stringValue;
}
public int getIntValue() {
return intValue;
}
public void setStringValue(String value) {
this.stringValue = value;
}
public void setIntValue(int value) {
this.intValue = value;
}
}
How can I get the field name of the Code whose value is "Gambia"?
-> it would be E0252
Thank you
You can search for it via a loop:
String val = "Gambia";
String field = "";
for (Code c : Code.values())
if (c.getStringValue().equals(val)) {
field = c.name();
break;
}
System.out.println(field);
Output:
E0252